lua metatable registration from c question -
hello have following bit of code seems work, i'm not sure why - i've built testclass follows
class testclass { int ivalue; public: int getivalue(); void setivalue(int &v); };
and registered testclass (bits left out actual functions they're pretty basic). it's registration of metatables i'm not following. (etivalue , setivalue c functions call class functions of same name)
static const struct lual_reg arraylib_f [] = { {"new", new_testclass}, {null, null} }; static const struct lual_reg arraylib_m [] = { {"set", setivalue}, {"get", getivalue}, {null, null} }; int luaopen_testclass (lua_state *l) { lual_newmetatable(l, "luabook.testclass"); lua_pushvalue(l, -1); /* duplicates metatable */ lua_setfield(l, -2, "__index"); lual_register(l, null, arraylib_m); lual_register(l, "testclass", arraylib_f); return 1; }
the bit don't understand i'm adding functions __index metatable when run
a = testclass.new() a:set(10) print(a:get())
then works expected. bit don't understand why set being called when think i've loaded in __index metatable? i've done or else?
tia
int luaopen_testclass (lua_state *l) { lual_newmetatable(l, "luabook.testclass"); //leaves new metatable on stack lua_pushvalue(l, -1); // there 2 'copies' of metatable on stack lua_setfield(l, -2, "__index"); // pop 1 of copies , assign // __index field od 1st metatable lual_register(l, null, arraylib_m); // register functions in metatable lual_register(l, "testclass", arraylib_f); return 1; }
that code equivalent example lua code:
metatable = {} metatable.__index = metatable metatable.set = function() --[[ stuff --]] end metatable.get = function() --[[ stuff --]] end
i assume 'new_testclass' c function sets metatable "luabook.testclass" returned table.
in code dont add functions metatable __index field. assign pointer metatable metatable's field named __index, , register set , functions it.
now, if set metatable value returned 'new_testclass' function (which assume do) - lets call value 'foo', , call foo:set(10), lua:
- checks there no such field 'set' in 'foo'
- sees 'foo' has metatable
- looks @ metatable's __index field - sees it's table
- checks if table assigned __index field has field 'set' , it's value function
- calls 'set' method passing 'foo' self parameter
i hope figure out whats going on here.
Comments
Post a Comment