lua-users home
lua-l archive

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

What is the best way to support something akin to table like fields on userdata, so you can have:

foo.status = 201
foo:puts("hello world")

where foo is a userdata?

I create a table and set it as the userdata's environment for storing fields. In the index and newindex metamethods, retrieve the field from the environment:

   int mynewindex( lua_State *L )
      lua_getfenv( L, 1 );
      lua_replace( L, 1 );
      lua_rawset( L, 1 );
      return 0;

   int myindex( lua_State *L )
      lua_getfenv( L, 1 );
      lua_pushvalue( L, 2 );
      lua_rawget( L, -2 );
      return 1;