Jump to content




String parsing help


  • You cannot reply to this topic
2 replies to this topic

#1 matejdro

  • Members
  • 324 posts

Posted 12 October 2012 - 05: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?

#2 Ditto8353

  • New Members
  • 138 posts

Posted 12 October 2012 - 05: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.

#3 GopherAtl

  • Members
  • 888 posts

Posted 12 October 2012 - 05: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






2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users