Lua need to split at comma

Jaron Bradley picture Jaron Bradley · Oct 9, 2013 · Viewed 57.7k times · Source

I've googled and I'm just not getting it. Seems like such a simple function, but of course Lua doesn't have it.

In Python I would do

string = "cat,dog"
one, two = string.split(",")

and then I would have two variables, one = cat. two = dog

How do I do this in Lua!?

Answer

marcus picture marcus · Oct 9, 2013

Try this

str = 'cat,dog'
for word in string.gmatch(str, '([^,]+)') do
    print(word)
end

'[^,]' means "everything but the comma, the + sign means "one or more characters". The parenthesis create a capture (not really needed in this case).