Loop with array + string

6

I'm trying to do something like:

a = {move1="oi", move2="oi2"}
for x=1, #a do
print(a.move..x)
end

I can not explain very well, but what I'm trying to do is this:

print(a.move..x)

getting print(a.move1) and next print(a.move2) , how can I do this?

    
asked by anonymous 02.11.2014 / 02:20

1 answer

7

I'll put two solutions for you.

The first one is based on the answer I've already provided . Pay close attention to the comment from lhf , the language's creator.

function table.map_length(t)
    local c = 0
    for k, v in pairs(t) do
         c = c + 1
    end
    return c
end

a =  { move1 = "oi", move2 = "oi2"}

for x=1, table.map_length(a) do
    print(a["move" .. x])
end

To help understand, know that the table you wrote is the same as writing:

a =  { ["move1"] = "oi", ["move2"] = "oi2"}

The syntax of a.move1 is the same as a["move1"] . Then you get what you want.

The second is the right way to do what you want.

a =  { move1 = "oi", move2 = "oi2"}

for k, v in pairs(a) do
    print(v)
end

See running on ideone . And no Coding Ground . Also I put it in GitHub for future reference .

One important note: In all of your codes you ignore the indentation in all the languages you are trying. This makes it difficult for you to read and especially for other people. It may sound silly, but the best programmers in the world find it hard to read non-indented codes. There is a cognitive difficulty in the way you write. And not only this, spacings in general help the reading. See the difference how I wrote.

    
02.11.2014 / 06:23