779 posts
Location
Kerbin
Posted 31 March 2014 - 04:13 PM
Hi!
Please help me with for loops with in pairs!
Thanks!
Example:
for k,v,in pairs do
Print(k..v)
Print("something")
end
What is this?
I don't know how works, what is this.
Thanks for answers!
Note: I'm only learning english, so please ignore my mistakes.
58 posts
Location
Seattle
Posted 31 March 2014 - 05:43 PM
example_table = {
1 = "hello",
2 = "oh yea",
3 = "bananna",
foo = 7,
bar = false,
}
for key, value in pairs(example_table) do
print("Key: "..k.." Value: "..v)
end
Result:
Key: 1 Value: hello
Key: 2 Value: oh yea
Key: 3 Value: bananna
Key: foo Value: 7
Key: bar Value: false
Also:
http://lua-users.org/wiki/ForTutorial
Edited on 31 March 2014 - 03:45 PM
1281 posts
Posted 31 March 2014 - 05:47 PM
Pairs(table) on it's own is an iterator function for getting keys and values in a table, it uses next(table,key) to do this. What the for loop does is repeatedly call the specified function until it returns nil, looping once for every call. Combining pairs and a for loops yields you every key and value pair in a table. Im curious though, why do you wish to know?
Edited on 31 March 2014 - 03:54 PM
1852 posts
Location
Sweden
Posted 31 March 2014 - 06:04 PM
With pairs loops you can also print the index name
for index, value in pairs( term ) do
print( index )
end
This would print everything in the term table( The name of the functions & variables )
Offtopic: Lol, I almost started a new topic because I thought text ads had been added to computercraft.info x)
Turns out that there was some malware that installed some sh*t called "safeweb" .-.
Edited on 31 March 2014 - 04:06 PM
350 posts
Posted 31 March 2014 - 10:41 PM
Basicaly the pair loop outputs all the content in a table. Its simple as that.
779 posts
Location
Kerbin
Posted 01 April 2014 - 03:31 PM
thanks very much ;)/> !
779 posts
Location
Kerbin
Posted 12 April 2014 - 07:14 AM
And one question,
It must be key, value or it can be somethingone,somethingtwo, too?
7508 posts
Location
Australia
Posted 12 April 2014 - 07:23 AM
they are simply the variable names, you can name them whatever you wish
for foo,bar in pairs( tTable ) do
print( foo, ' : ', bar )
end
another example is if you're only after the key then you could do
for key in pairs( tTable ) do
print( key )
end
it is common for programmers in Lua to name variables they have no interest with underscores for better readability, so lets say we only want the value we could do
for _,value in pairs( tTable ) do
print( value )
end
there are cases where you can have more than 2 values returned, but I won't confuse you with that one ;)/>