Page 1 of 1
what is this code doing?
Posted: Thu Feb 25, 2010 8:25 pm
by gurke93
In a demo application i read this:
Code: Select all
function Options:update(dt)
for n,b in pairs(self.button) do
b:update(dt)
end
end
and my question ist what does make the "for n,b in pairs [...]". Why i cant write only b:update(dt)? i found this code not only in the update function. For example in the draw function i found it, too.
PLease help!
Re: what is this code doing?
Posted: Thu Feb 25, 2010 8:30 pm
by Robin
Well, you need to iterate over the table self.button, which contains tables which have a method called update.
Re: what is this code doing?
Posted: Thu Feb 25, 2010 9:26 pm
by gurke93
Oh thanks. Can you explain the funciton in pais for noobs please ?
Re: what is this code doing?
Posted: Thu Feb 25, 2010 9:40 pm
by Virox
wel self.button is actually a metatable existing out of keys and values
n = key and b = value (this example a button)
the code itself is a for loop, iterating through every key of the table (in this example every button added to the table)
b:update(dt) <-- this will update the button
Someone correct me if I made mistakes.
Re: what is this code doing?
Posted: Fri Feb 26, 2010 6:27 am
by bmelts
pairs iterates through all of a table's keys. Programming in Lua has more detailed information, in particular,
here.
If you want an explanation of how pairs (and its cousin ipairs, which only works on arrays) works, the best resource is probably, again, Programming in Lua. In specific,
the section on the generic for.