Here's how the generic-for works in a nutshell:
local t = {'a', 'b', 'c', 'd', 'e'}
for key, value in ipairs(t) do
print(key, value)
end
A table is simply a set of key/value pairs. The generic for lets you access these pairs as you iterate over each pair in the table.
They key concept to understand here is that of an "iterator". Above, ipairs() is an iterator. You give it a table, it does some stuff (see non-nutshell explanation below), and it returns new values to your left-side variables for each iteration until you're done. ipairs() goes over consecutive integer keys (i.e. 1, 2, 3, 4) until there's no entry for that key (i.e. t[num] is nil). pairs() goes over absolutely every entry in a table, but you have no guarantee it will come out in any particular order.
Your code above would be:
for name, details in pairs(stellarobjects) do
print(name, " -- ", details)
end
--[[ Output: (example)
Resolute -- table: 11111111
MatteBlackTaxi13 -- table: 222222
Krakana -- table: 33333333
--]]
Notice that it won't print out the contents of the details value. To inspect a table, I recommend using require("tprint") like so:
require("tprint")
tprint(stellarobjects)
Note that tprint() is not an iterator, so you don't use it as for k,v in tprint(t) do end. It's just a regular function, like print(). :)
If you're still reading and want more, here's an extended explanation. I suggest reading PiL chapter 7 for more details on iterators [1], but here's a cursory overview of the details.
An iterator like pairs() and ipairs() is really an iterator factory. Iterator factories return a function, and it's that function that's called every iteration by the generic-for loop. For example:
local iter, tbl, state = pairs(t)
for key, value in iter, tbl, state do
print(key, value)
end
Now things are getting interesting, eh? An iterator factory return three values: an iterator function, the object being iterated over, and some state. Lets simulate what a loop that uses pairs() does:
-- pairs() returns a function that already exists, called next().
local t = {foo = 1, bar = 42, baz = 50}
local key, value = nil, nil
while true do
key, value = next(t, key)
if key == nil then
break
end
print(key, value)
end
Do you see what's happening? This is almost exactly what happens inside the for-loop implementation, except it's not limited to next().
I highly recommend PiL if you want to learn more about iterators, or just Lua in general. :)
[1] http://www.lua.org/pil/7.html |