Fairly offtopic, but
pairs is a Lua language function to iterate over the key/value pairs in a table.
k and
v are the variables typically assigned to the key and the value, respectively, though you can call them anything you want.
Code:
local myTable = {
rose = "red",
violet = "blue",
}
for k, v in pairs(myTable) do
print(k.."s are "..v)
end
-- ^ This will print "roses are red" and "violets are blue" in no particular order.
-- You can also give your variables more descriptive names if you like:
for flower, color in pairs(myTable) do
print(flower.."s are "..color)
end
-- ^ This does exactly the same thing.
Note that the key/value pairs are returned in an undefined order, which will usually be consistent (eg. if you loop over the same table twice in a row, the order will probably be the same) but can't be relied on for anything; if you need to preserve the order of things your table, use only index/value pairs (t[1] = "z", not t["x"] = "y") and loop over it sequentially:
Code:
local myOrderedTable = {
"kittens",
"puppies",
"baby seals",
}
-- Get the size of the table using the # operator, and do a simple loop:
for i = 1, #myOrderedTable do
-- Get the value at this position:
local v = myOrderedTable[i]
print(v.."are fuzzy!")
end
You may see people using
ipairs instead of a simple
i=a,b loop like the one shown above. Don't do this. It's slow beacuse it's a function call, and it doesn't offer any advantage (or even any functional difference) whatsoever. Similarly, don't use
tinsert(tbl, val) to add a value to the end of a table; use
tbl[#tbl+1]=val instead.
Also note that tables can contain both index/value and key/value pairs, but the # operator (and
ipairs) will only count the indexed values (not the keyed ones), and only starting from 1 and incrementing sequentially. If your table doesn't have anything at index 1, it's considered to have 0 indexed values. If your table has values at indices 1, 2, 3, and 7, it's considered to have 3 indexed values. Always use
tremove to delete indexed values, and
tinsert to insert indexed values anywhere other than at the end of the list, so you don't get holes in your list.
One handy effect of being able to mix indices and keys is that you can store both key/value pairs,
and the order you want to handle them, in the same table. For example, alphabetizing:
Code:
local tbl = {
"banana",
"apple",
"cat",
["banana"] = "yellow fruit",
["apple"] = "round fruit",
["cat"] = "small furry animal",
}
-- You can use things like table.sort to manipulate the indexed values:
table.sort(tbl)
-- ^ Now the indexed values are in alphabetical order.
for i = 1, #tbl do
local k = tbl[i]
local v = tbl[k]
print("A "..k.." is a "..v)
end
(Should probably report your post and ask a moderator to split it and this reply to their own thread.)