lua-users home
lua-l archive

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


<RLake@oxfam.org.uk> writes:

[The "is nil present in a table" problem]

> One solution I've used to problems like this is to define a table of
> tables.
>
> Instead of having the table {key1=val1, key2=val2, ... } you can use
> {keys={key1=1, key2=2,...},vals={val1, val2,...}}
>
> Then instead of writing struct[key], you can say
> struct.vals[struct.keys[key]]. That's a little hard to type all the time,
> but it's easy enough to provide gettable/settable methods which do it.
>
> With this system, you can distinguish between keys which are not present
> (struct.keys[key] is nil) and keys which are present but are nil
> (struct.vals[struct.keys[key]] is nil).

Yeah; the trick Rob Leslie suggested was {key1={key1, value}, key2={key2,
value}} .

> The other advantage to this methodology is that the original ordering of
> keys is preserved, although it's not preserved in a particularly useful
> fashion. I have at times resorted to putting a third element in the
> structure which is the inverse of the first one; i.e. it maps indices to
> keys. This allows iteration to proceed in the order of insertion, which
can
> be extremely useful.

That's an interesting idea; thank you for describing it.

> See my page on ExtendingForAndNext for an experiment on building
> non-standard iterations into Lua.

( http://lua-users.org/wiki/ExtendingForAndNext )

I really like ExtendingForAndNext; for starters, it scratches my "for
i=1,getn(l) do local v=l[i]" itch.  It also seems very much in the current
spirit of Lua, which isn't true of all the language extensions floating
around.  For instance, unified methods significantly changes the semantics
of ":" away from being syntactic sugar, and loses some of the "everything's
a table" flavor of current Lua object programming.  I don't know if this is
good or bad, but I have to think about it; ExtendingForAndNext seems
obviously in the Lua theme.

I would like ExtendingForAndNext to show up in Lua 4.1.  I don't think I can
use it for many of my projects if it's not in the mainline language
implementation---just watch how many people use the all-lua XML tree parser
that I just posted instead of building lxp and getting something that may
actually survive future XML-RPC implementations (CDATA, anyone?)

Jay