lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On 21-Mar-05, at 2:15 PM, PA wrote:

No. At least not for me. I don 't see any function I'm passing a parameter to. This is too confusing for me. I therefore try to avoid it.

Let me try to make it easier then.

  for <vars> in method, object do

Arguably, this would have been better written with 'of' instead of ',' but the ',' allows for the use of computed messages.

The object method is invoked to produce the next element of the loop. It is, therefore, an iterator function being specified to the for loop. It takes a single argument, beyond the self argument, which is the iteration key; it returns the next iteration key and whatever values might be associated with it, if any. These values, starting with the iteration key, are bound to the local variables.

At first glance there are 4 different ways to write a "for" loop ( "=", "in", "in ipairs()", "in pairs()" ). That's 3 too many for me :}

Just two. However, it is common to use functions to create the message, as described above.

So, for example, pairs(t) is no more complicated than this:

function pairs(t) return next, t end

and you could, if you wished, just write that:

for k, v in next, t do ... end

By the way, I lied a little bit. You can actually specify the first iteration-key argument to the iterator function as well, but by convention iterator functions use nil as the "start of iteration" marker.