Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua need to split at comma

Tags:

split

match

lua

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

like image 210
Jaron Bradley Avatar asked Oct 09 '13 03:10

Jaron Bradley


People also ask

How do you slice a string in Lua?

A very simple example of a split function in Lua is to make use of the gmatch() function and then pass a pattern which we want to separate the string upon.

How do you split a comma in JavaScript?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do you split a comma in Python?

You can use the Python string split() function to split a string (by a delimiter) into a list of strings. To split a string by comma in Python, pass the comma character "," as a delimiter to the split() function. It returns a list of strings resulting from splitting the original string on the occurrences of "," .


2 Answers

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

like image 59
marcus Avatar answered Oct 07 '22 22:10

marcus


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("([^,]+),([^,]+)") 
like image 42
catwell Avatar answered Oct 07 '22 21:10

catwell