Lua need to split at comma

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).


If you can use libraries, the answer is (as often in Lua) to use Penlight.

If Penlight is too heavy for you and you just want to split a string with a single comma like in your example, you can do something like this:

string = "cat,dog"
one, two = string:match("([^,]+),([^,]+)")

Tags:

Split

Lua

Match