how to convert a string to a table

i have a string
string = “jeff,10,sue,5,priscilla,4,tanner,3,bill,2,tim,1”
i need to convert it to a table
[import]uid: 7911 topic_id: 12555 reply_id: 312555[/import]

If the strings are in a text file, one element per line, you could do this:

[lua]t = {}
for line in io.lines(“my.txt”) do
t[#t + 1] = line
end[/lua]

If they aren’t in a text file, try something like this:

[lua]-- explode(separator, string)
function explode(d,p)
local t, ll
t={}
ll=0
if(#p == 1) then return {p} end
while true do
l=string.find(p,d,ll,true) – find the next d in the string
if l~=nil then – if “not not” found then…
table.insert(t, string.sub(p,ll,l-1)) – Save it in our array.
ll=l+1 – save just after where we found it for searching next time.
else
table.insert(t, string.sub(p,ll)) – Save what’s left in our array.
break – Break at end, as it should be, according to the lua manual.
end
end
return t
end

local myTable = explode(",", str)[/lua]

That last bit was pulled from here: http://lua-users.org/wiki/SplitJoin

Jay
[import]uid: 9440 topic_id: 12555 reply_id: 45880[/import]

thanks jay
i also found this http://lua-users.org/wiki/CsvUtils
which i think will work but ill try tomorrow been up bout 20 hours now [import]uid: 7911 topic_id: 12555 reply_id: 45881[/import]

I assume you just wanted the things and not the commas

testtab = {}--create table to put them in teststr = "jeff,10,sue,5,priscilla,4,tanner,3,bill,2,tim,1"--original string teststr2 = string.gsub(teststr, "%,", " ")--replace commas with spaces print("teststr2 ", teststr2) --read in and push to table for word in teststr2:gmatch("%w+") do table.insert(testtab, word) end --print table contents for i = 1, #testtab do print("table ", testtab[i]) end [import]uid: 2131 topic_id: 12555 reply_id: 45885[/import]

@Rob, that is a bit of a dangerous assumption, if a name like jack frost came up, the regex would fail. instead if the , was included as part of the regex, it would be safer.

cheers,

?:slight_smile: [import]uid: 3826 topic_id: 12555 reply_id: 45899[/import]

lol, you are indeed correct, but he said he has a string he needed to convert it to a table, that converts it as requested.

Doing it properly as you detailed is better of course and much more flexible, that’s why I only use your propertyBag, and didn’t write it! Cheers by the way, makes life so much easier!

Rob [import]uid: 2131 topic_id: 12555 reply_id: 45902[/import]

thanks guys I’ve got it working [import]uid: 7911 topic_id: 12555 reply_id: 45910[/import]