Skip to main content
Inspiring
December 10, 2015
Question

lua, split string

  • December 10, 2015
  • 1 reply
  • 1502 views

This is almost embarrassing to ask about but I'm stuck. I'm trying to split a string at whitespace. I'm broadly assuming that string.gmatch() returns an array, which it appears to do in the loop example below. However if I try and grab an element from the return value it throws up an error, telling me it's a function. Can anyone help:?

local example = "an example string"

-- works as expected.
 for i in string.gmatch(example, "%S+") do
  Debug.logn(i)
end

-- tells me s is a function
Debug.logn( string.gmatch( example, "%S+" ) )

-- tells me I'm trying to index a function value
Debug.logn( s[1] ) 
This topic has been closed for replies.

1 reply

johnrellis
Legend
December 11, 2015

string.gmatch() returns an iterator (not an array) that can only be used in a for loop.   You may want to use one of the other matching functions:

That comes from the Lua 5.1 Short Reference, which I always keep close at hand.

kimaldisAuthor
Inspiring
December 25, 2015

Thanks John.