Position of "letter" in string

1

How can I get the position of a letter in a string. EX:

 a = "x  x  x"

I would like to get the position of each x. I tried using the string.find, but it just picked up the first one.

    
asked by anonymous 30.10.2014 / 11:31

2 answers

5
a = "x  x  x"

pos = 0
while 1 do
    pos = a:find( "x", pos + 1 )
    if not pos then break end
    print( pos )  -- poderia armazenar numa tabela
end

Output:

1
4
7

See working at IDEONE .

    
30.10.2014 / 11:56
3

Try also

a = "x  x  x"
for k in a:gmatch("()x") do
    print(k)
end

Note the empty catch () , which captures the position.

    
31.10.2014 / 17:17