Converting a string into a table

Posted by Gaznox on Sun 27 May 2007 05:19 AM — 3 posts, 17,585 views.

#0
I was reading on how to use tables and I noticed that there is a table.concat command that strings together table values. Is there anything that does the reverse as in change:
the,quick,brown,fox,jumped

into:
t =
{
"the",
"quick",
"brown",
"fox",
"jumped",
}
USA #1
If you know the string ahead of time, you can just do:

t = {"the","quick","brown", ...}


But I'm guessing you don't know ahead of time what the string is. In that case, you should use string.gmatch:


[david@thebalrog:~]$ cat test.lua
#!/usr/bin/lua

s = "hello,world,from,Lua"
for w in string.gmatch(s, "([^,]+)") do
    print(w)
end


[david@thebalrog:~]$ lua test.lua
hello
world
from
Lua



EDIT: to complete the example, instead of printing the words, you'd add them to a table using table.insert, for example.
Amended on Sun 27 May 2007 06:51 AM by David Haley
Australia Forum Administrator #2
See:

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