lua-users home
lua-l archive

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


Hi !

**Not** tested at all, hope it helps:

int mylen(lua_State *L, int p)
{
   int pos = (p > 0 || p <= LUA_REGISTRYINDEX ? p : lua_gettop(L) + p + 1);
   int result = 0;
   if (lua_isuserdata(L,pos) && !lua_islightuserdata(L,pos))
   {
       int result = 0;
       luaL_getmetafield(L, pos, "__len");
       if (lua_isfunction(L,-1))
       {
           lua_pushvalue(L,pos); // push the object
           lua_call(L, 1, 1); // call __len(obj)
           result = lua_tointeger(L,-1); // get the result
           lua_pop(L,1); // remove returned value
       }
       lua_pop(L,1); // remove metafield or nil
   }
   else
   {
       // default behaviour
       result = lua_objlen(L, pos);
   }
   return result;
}


On 11/16/06, Jérôme VUARAND <jerome.vuarand@gmail.com> wrote:
2006/11/15, Shmuel Zeigerman <shmuz@actcom.co.il>:
> lua_objlen

Why isn't there one for user data ? lua_objlen return the block size
of a userdata, whereas #ud in Lua calls the "len" metamethod. Is there
an equivalent of lua_objlen that push its result on the stack and that
calls metamethods on userdata if there is any ?

The only fallback I found was to create a length function in Lua :
----
length = function(obj)
   return #obj
end
----
and to lua_call it from my C code. But I can't figure out how to port
that function to C, there seems to be a missing API function (unless I
emulate the behaviour of the # operator by accessing metatable
myself).



--
 Jose L. Hidalgo Valiño (PpluX)
 ---- http://www.pplux.com ----