Parsing

Posted by Terry on Sat 01 Aug 2009 04:09 AM — 6 posts, 30,372 views.

USA #0
What would be the best way of parsing a list? If there's no function, here's an algorithm I've written. My problem is that I don't know how to do this in Lua.

Is the delim not in the string?
  True:
    return the string as a table
  False:
    size = the number of times the delim is found in the string + 1
    allocate a table to `size' elements
    While there is a delim in the string:
      store all the characters before the first delim in the next open element
      remove everything up to and including the first delim in the string
    return the table


Thanks for the help. :)
Amended on Sat 01 Aug 2009 04:20 AM by Terry
Germany #1

local teststr = "1st,2nd,3rd,"
local delim = ','
local t = {}
for l in string.gmatch(teststr, "[^"..delim.."]+") do
 t[#t+1] = l
end

the above code works only with 1-character long delim. Also, in case "a,,b" it just skips the 2nd ',' (there can be cases, that You wants to have an extra EMPTY or nil entry)
USA #2
Thanks :) By the way, how could you then print the list so it looks like "1st, 2nd, and 3rd"? Or, for example, if t only had two elements, it show "1st and 2nd".

Edit: The issue is not knowing how many elements are in t beforehand.

Oh, and also, how would I go about deleting the first element after I'm finished with it? Would I just use table.remove(t,1)?
Amended on Sat 01 Aug 2009 04:38 AM by Terry
Germany #3

for i = 1, #t-2 do
	Tell(t[i]..delim..' ')
end
	Tell(t[#t-1]..' and '..t[#t]..'\n')

Tell is like io.write in Lua.
Edit:
You can just try it :)
And/or read the manual:
Quote:

table.remove (table [, pos])

Removes from table the element at position pos, shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for pos is n, where n is the length of the table, so that a call table.remove(t) removes the last element of table t.
Amended on Sat 01 Aug 2009 05:05 AM by Erendir
Australia Forum Administrator #4
This may or may not be what you want to parse a delimited list:

http://www.gammon.com.au/scripts/doc.php?lua=utils.split
USA #5

require 'tprint'

tbl = utils.split(delimitedstring, delim)

tprint(tbl)