tags:

views:

1410

answers:

2

I have a string in Lua and want to iterate individual characters in it. But none code i have tried is working and 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
+2  A: 

If you're using Lua 5, try:

for i = 1, string.len(str) do
    print( string.sub(str, i, i) )
end
Aaron Saarela
+8  A: 

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.

RBerteig
Thanks. About lpeg module you have mentioned - does it save tokens positions in original text after tokenization? The task i need to perform is to syntax highlight specific simple language in scite via lua (with no compiled c++ parser). Also, how to install lpeg? Seems it has .c source in distribution - does it need to be compiled alongside lua?
Eye of Hell
Building lpeg will produce a DLL (or .so) that should be stored where require can find it. (i.e. somewhere identified by the content o f the global package.cpath in your lua installation.) You also need to install its companion module re.lua if you want to use its simplified syntax. From an lpeg grammar, you can get callbacks and capture text in a number of ways, and it is certainly possible to use captures to simply store the location of match for later use. If syntax highlight is the goal, then a PEG is not a bad choice of tool.
RBerteig