This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
matejdro's profile picture

String parsing help

Started by matejdro, 12 October 2012 - 04:21 PM
matejdro #1
Posted 12 October 2012 - 06:21 PM
Here is what I'm trying to do:


inputString = "1 20 3 45 5"

while inputString ~= nil do
local spaceLocation = string.find(inputString, " ")

if spaceLocation ~= nil then
   number = tonumber(string.sub(inputString,1, spaceLocation))
   inputString = string.sub(inputString, spaceLocation + 1)
else
  number = tonumber(inputString)
  inputString = nil
end

print(number)
end

Basically, I want to retreive all numbers from string. What I do is search for space, retreive number and then trim string.

It works great for the first number, but then string.find would start returning wierd values like string was never trimmed.

Any idea what am I doing wrong?
Ditto8353 #2
Posted 12 October 2012 - 06:23 PM
Sorry, my first code was not right…


numbers = {}
for n in string.gmatch(inputString,"(%d+)") do
   table.insert(numbers,n)
end

This will put all numbers into the 'numbers' table.
GopherAtl #3
Posted 12 October 2012 - 06:48 PM
You're running into a bug with jlua, the implementation of lua computercraft uses. You can fix your existing code by appending "" to the string after calling string.sub(), ex…


inputString=string.sub(inputString,spaceLocation+1)..""

:edit: just noticed ditto's post was editied since I initially replied, at the time of my post it just said "Hmmm…" which I thought was very unconstructive lol.
Ah well. Now you have two answers.

However, I should note this is clearly a job for lua patterns.

Same thing, but done with lua patterns and string.gsub()…
Spoiler

local inputString="11 20 14 5"
local numbers={}
string.gsub(inputString,"%d+",function(n) numbers[#numbers+1]=n end)
for i=1,#numbers do
  print(i..":"..numbers[i])
end

even better than gsub for this would be gmatch, but for some reason I'm thinking it's not even implemented in luaj? I may be wrong, can only test with codepad right now, but this works in normal lua…

local inputString="11 20 14 5"
for n in string.gmatch(inputString,"%d+") do
  print(n)
end