How to iterate individual characters in Lua string

lua

I have a string in Lua and want to iterate individual characters in it. But no code I've tried works and the official manual only shows how to find and replace substrings 🙁

str = "abcd"
for char in str do -- error
  print( char )
end

for i = 1, str:len() do
  print( str[ i ] ) -- nil
end

Best Solution

In lua 5.1, you can iterate of the characters of a string this in a couple of ways.

The basic loop would be:

for i = 1, #str do
    local c = str:sub(i,i)
    -- do something with c
end

But it may be more efficient to use a pattern with string.gmatch() to get an iterator over the characters:

for c in str:gmatch"." do
    -- do something with c
end

Or even to use string.gsub() to call a function for each char:

str:gsub(".", function(c)
    -- do something with c
end)

In all of the above, I've taken advantage of the fact that the string module is set as a metatable for all string values, so its functions can be called as members using the : notation. I've also used the (new to 5.1, IIRC) # to get the string length.

The best answer for your application depends on a lot of factors, and benchmarks are your friend if performance is going to matter.

You might want to evaluate why you need to iterate over the characters, and to look at one of the regular expression modules that have been bound to Lua, or for a modern approach look into Roberto's lpeg module which implements Parsing Expression Grammers for Lua.