lua-users home
lua-l archive

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

Hi Thomas,

2007/4/19, Thomas Lauer <>:
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.

 Jose L. Hidalgo Valiño (PpluX)
 ---- ----