DSLua Community
Welcome, Guest. Please login or register.
May 21, 2012, 08:27:28 PM
1371 Posts in 262 Topics by 33109 Members
Latest Member: Limewire Download
DSLua Community  |  DSLua - Best scripting language for Nintendo DS  |  Need Help?  |  I can't understand the working of the generic for loop « previous next »
Pages: [1]
Author Topic: I can't understand the working of the generic for loop  (Read 1102 times)
suloku
New Moon
*
Posts: 8


« on: June 20, 2007, 06:29:50 AM »

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.
Logged
H3xo
New Moon
*
Posts: 3


« Reply #1 on: June 22, 2007, 06:18:27 AM »

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.
Code:
for Key,Value in pairs({"Key1" = 1, "Key2" = 2, "ThisIsAKey" = "ThisIsAValue"}) do
    print("Key: "..Key.." Value: "..Value)
end
Would print
Quote
Key: Key1 Value: 1
Key: Key2 Value: 2
Key: ThisIsAKey Value: ThisIsAValue

First argument is the key, second argument is the value.

Another example
Code:
local Table = {4,3,2,1}
for k,v in pairs(Table) do
    print(k.." "..v)
end
Would print
Quote
1 4
2 3
3 2
4 1

You can also do for,do loops like so
Code:
for i = 0, 24 do
    print(i)
end
That would output
Quote
1
2
3
4
5
6
7
..
..
24

Hope that helps Cheesy
Logged
suloku
New Moon
*
Posts: 8


« Reply #2 on: June 24, 2007, 05:33:51 PM »

Thanks, now I understand it far better, I just need to look deeper in pairs() and ipairs() functions to fully understand that loops
Logged
Pages: [1]
« previous next »
    Jump to: