How should I bind lua functions to C++ functions? -
i have class called entity, has many functions onpickup, ondrop, onuse etc. want is, write script defines of these functions , make them callable c++ functions. functions defined in c++ calling corresponding lua functions have functionality.
but here's problem, want every script write, every entity in program working in it's own scope.
i'm using luabind, , have no prior experience lua, i'm little lost here.
i don't use lua bind may help. idea register lua functions in c++ class , keep reference lua function in c++ class.
to define lua function callable c/c++ use lual_ref store reference callback function in c++ object.
// little helper function template <typename t> t *lua_getuserdata(lua_state *l) { assert(lua_isuserdata(l, 1) == 1); t **v = (t **) lua_touserdata(l, 1); assert(v != null); return *v; } int lua_formregistermethods(lua_state *l) { entity *f = lua_getuserdata<entity>(l); assert(lua_istable(l, 2) == 1); // check next parameter table lua_pushvalue(l,2); // dup table f->luatable = lual_ref(l, lua_registryindex); // keep reference table lua_getmetatable(l, 2); // metatable lua_pushstring(l, "onclick"); lua_rawget(l, -2); // onclick lua function f->luamethod = lual_ref(l, lua_registryindex); // save reference return 0; }
and can lua method in c++ event
lua_rawgeti( luainstance->l, lua_registryindex, luamethod ); assert(lua_isfunction(luainstance->l, -1) == 1);
now can call function self set table saved earlier. hth
Comments
Post a Comment