Loop with array + string

Asked

Viewed 125 times

7

I’m trying to do something like:

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

I can’t explain it very well, but what I’m trying to do is this:

print(a.move..x)

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

1 answer

8


I will put two solutions for you.

The first is based on answer I have already provided you. Pay close attention to the comment of lhf, the creator of language.

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 thing 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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.


One important note: in all your codes you ignore the indentation in all the languages you are trying. This makes it difficult for you to read, and especially from other people. It may sound silly, but the best programmers in the world have trouble reading unidentified code. There is a cognitive difficulty in the way you write. And not only that, spacing in general helps reading. See the difference as I wrote.

  • I’ll start to worry more about that. As for the answer, it’s perfect.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.