Split A Sting In Lua
Heads-Up
there's a better function to use in:
id: 2xgl9090
This works, but the other is more robust
Splitting a string in lua can be done by matching everything except for the separator in a `.gmatch()`` capture group like this:
Code
local line = "alfa bravo charlie"
local words = {}
for word in string.gmatch(line, "%S+") do
table.insert(words, word)
end
print(words[1])
print(words[2])
print(words[3])
Results
alfa bravo charlie
Old Notes
These are older notes that I need to go back and look over
via: http://lua-users.org/wiki/SplitJoin
Another approach
Code
function mysplit (inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={}
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
table.insert(t, str)
end
return t
end
input_string = 'this is it'
base_table = mysplit(input_string, " ")
for i=2, #base_table do
print(base_table[i])
end
via: https://stackoverflow.com/a/7615129/102401