luasplitmatch

Lua need to split at comma


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!?


Solution

  • 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("([^,]+),([^,]+)")