lua-users home
lua-l archive

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


Hi,

David Given wrote:
> [...] getchildren, however, gets a list of 
> a particular object's children. What's the best way of returning this?

As Daniel Silverstone already pointed out, an iterator is usually the
most flexible approach. You can easily extend this by providing tree
traversals (in different orders) or even XQuery-like iterators ('return
all siblings of this object that are buttons'). But don't get too fancy
unless you really need to.

>  child1, child2, child3 = object:getchildren()

You probably already know this, but the 'adjust return values' feature
of Lua comes handy here: If the function returns less objects than there
are variables, the remaining variables are set to nil. It may be sufficient
to provide 'just enough' variables and then check if they are not nil before
using them.

>  childarray = {object:getchildren()}
> 
> ...which is a bit ugly.

Why? It is pretty fast, too. Certainly faster than constructing an array
in the called function. Even when this is a C function (because the SETLISTO
opcode calls internal functions to construct the table).

>  child1, child2, child3 = unpack(object:getchildren())

Well, this is slow. In part because of the additional function call and
in part because unpack() is not very efficient for your purpose (it calls
luaL_getn()). As far as Lua APIs are concerned, this one looks 'unnatural'.

>  childarray = object:getchildren()

This may be ok if you have to return more children than can reasonably
be stored on the stack. But an iterator seems more appropriate then.

I suggest to provide both an iterator and a return-all-children-on-stack
function for convenience.

Bye,
     Mike