I'm reading the lua programming manual, but I can't get how a generic loop works. I just want to know what exactly happens inside a loop like this:
-- print all values of array `a'
for i,v in ipairs(a) do print(v) end
Ok, tis prints all values of the array "a", but I don't get the sintax, maybe because of that "in" in there and the function ipairs(), which I don't know exactly what it does (and I couldn't find out).
Same for this example:
-- print all keys of table `t'
for k in pairs(t) do print(k) end
They say that this kind of for loops are powerful, but even if I can blindy use them and get the correct outputs, I want to know what happens in there and how to properly use them.
Thanks.
for Key,Value in pairs({"Key1" = 1, "Key2" = 2, "ThisIsAKey" = "ThisIsAValue"}) do
print("Key: "..Key.." Value: "..Value)
end
Would print
Key: Key1 Value: 1
Key: Key2 Value: 2
Key: ThisIsAKey Value: ThisIsAValue
First argument is the key, second argument is the value.
Another example
local Table = {4,3,2,1}
for k,v in pairs(Table) do
print(k.." "..v)
end
Would print
1 4
2 3
3 2
4 1
You can also do for,do loops like so
for i = 0, 24 do
print(i)
end
That would output
1
2
3
4
5
6
7
..
..
24
Hope that helps
