[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Why no pairs() for userdata, __len for tables?
- From: Mark Hamburg <mhamburg@...>
- Date: Thu, 19 Apr 2007 11:53:15 -0700
Except that you can't get to userdata metatables from pure Lua. But one
could certainly replace pairs with a C function that did this and you don't
need to patch the Lua sources to do it.
on 4/19/07 6:39 AM, Jose Luis Hidalgo at firstname.lastname@example.org wrote:
> Hi Thomas,
> 2007/4/19, Thomas Lauer <email@example.com>:
>> I have a userdatum that looks (almost) like a Lua table: accesses are
>> caught through __index/__newindex/__len. (Nifty, this metastuff.)
>> What I can't (but would like to) do, is iterating over this table with
>> the standard functions. Writing my own iterator is easy enough but it
>> feels inconsistent: with a "normal" table I'd use pairs() (or ipairs()).
>> There may be very good reasons why there's no metamethod support for
>> this. If so, can anyone light a candle?
> I'm not sure if is there any reason, but maybe this can help you, it
> is a replacement of pairs written in pure lua.
> local _pairs = pairs
> function pairs (value)
> if type(value) == "userdata" then
> local g = getmetatable(value)
> return g.__pairs(value)
> return _pairs(value) -- original
> makes a closure with the original pairs function, and in case the
> given value is an userdata then tries to access its metatable and ask
> for a "__pairs" function.... otherwise uses the original pairs.
> To make this work, you should return three values, a function, an
> state, and an initial value... as is explained in the section 2.4.5 of
> the lua manual.
> Jose L.