Alex Rivera | Logout

How to iterate individual characters in Lua string?

Asked 2009-05-06T10:55:36.657
130

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
lua
Edit
Report

1 Answer

14

If you're using Lua 5, try:

for i = 1, string.len(str) do
    print( string.sub(str, i, i) )
end
answered 2009-05-06T13:05:41.117

Your Answer