43

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

1

7 Answers 7

74

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

38

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

Add this split function on the top of your page:

function string:split( inSplitPattern, outResults )
  if not outResults then
    outResults = { }
  end
  local theStart = 1
  local theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
  while theSplitStart do
    table.insert( outResults, string.sub( self, theStart, theSplitStart-1 ) )
    theStart = theSplitEnd + 1
    theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
  end
  table.insert( outResults, string.sub( self, theStart ) )
  return outResults
end

Then do as follows:

local myString = "Flintstone, Fred, 101 Rockledge, Bedrock, 98775, 555-555-1212"

local myTable = myString:split(", ")
for i = 1, #myTable do
   print( myTable[i] ) -- This will give your needed output
end

For more information, visit : Tutorial: Lua String Magic

Keep Coding...............:)

6

-- like C strtok, splits on one more delimiter characters (finds every string not containing any of the delimiters)

function split(source, delimiters)
        local elements = {}
        local pattern = '([^'..delimiters..']+)'
        string.gsub(source, pattern, function(value) elements[#elements + 1] =     value;  end);
        return elements
  end

-- example: var elements = split("bye# bye, miss$ american@ pie", ",#$@ ") -- returns "bye" "bye" "miss" "american" "pie"

5

To also handle optional white space you can do:

str = "cat,dog,mouse, horse"
for word in str:gmatch('[^,%s]+') do
    print(word)
end

Output will be:

cat
dog
mouse
horse
1

Functions like string.split() are largely unnecessary in Lua since you can express string operations in LPEG. If you still need a dedicated function a convenient approach is to define a splitter factory (mk_splitter() in below snippet) from which you can then derive custom splitters.

local lpeg      = require "lpeg"
local lpegmatch = lpeg.match
local P, C      = lpeg.P, lpeg.C

local mk_splitter = function (pat)
  if not pat then
    return
  end
  pat            = P (pat)
  local nopat    = 1 - pat
  local splitter = (pat + C (nopat^1))^0
  return function (str)
    return lpegmatch (splitter, str)
  end
end

The advantage of using LPEG is that the function accepts both valid Lua strings and patterns as argument.

Here is how you would use it to create a function that splits strings at the , character:

commasplitter = mk_splitter ","

print (commasplitter [[foo, bar, baz, xyzzy,]])
print (commasplitter [[a,b,c,d,e,f,g,h]])
1

This is how I do that on mediawiki:

str = "cat,dog"
local result = mw.text.split(str,"%s*,%s*")
-- result[0] will give "cat", result[1] will give "dog"

actually, if you don't care spaces, you can use:

str = "cat,dog"
local result = mw.text.split(str,",")
-- result[0] will give "cat", result[1] will give "dog"

The API used here is implemented in Scribunto MediaWiki extension. Here is the split() method reference documentation and here is the source code for that. It relies on a lot of other capabilities in Scribunto's Lua common libraries, so it will only work for you if you are actually using MediaWiki or plan to import most of the Scribunto common library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.