[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- 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.
Mark
on 4/19/07 6:39 AM, Jose Luis Hidalgo at joseluis.hidalgo@gmail.com wrote:
> Hi Thomas,
>
> 2007/4/19, Thomas Lauer <thomas.lauer@virgin.net>:
>> 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.
>
> do
> local _pairs = pairs
> function pairs (value)
> if type(value) == "userdata" then
> local g = getmetatable(value)
> return g.__pairs(value)
> else
> return _pairs(value) -- original
> end
> end
> end
>
> 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.
>
>
> Cheers,
> Jose L.