what is this code doing?

Showcase your libraries, tools and other projects that help your fellow love users.
Post Reply
gurke93
Prole
Posts: 5
Joined: Fri Feb 19, 2010 7:40 pm

what is this code doing?

Post 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!
User avatar
Robin
The Omniscient
Posts: 6506
Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:

Re: what is this code doing?

Post by Robin »

Well, you need to iterate over the table self.button, which contains tables which have a method called update.
Help us help you: attach a .love.
gurke93
Prole
Posts: 5
Joined: Fri Feb 19, 2010 7:40 pm

Re: what is this code doing?

Post by gurke93 »

Oh thanks. Can you explain the funciton in pais for noobs please ?
User avatar
Virox
Citizen
Posts: 64
Joined: Thu Jan 07, 2010 6:24 pm

Re: what is this code doing?

Post 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.
User avatar
bmelts
Party member
Posts: 380
Joined: Fri Jan 30, 2009 3:16 am
Location: Wiscönsin
Contact:

Re: what is this code doing?

Post 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.
Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests