luabind でC++からLuaのclassを扱う
luabindを使うと、lua側でclassが使えるようになります。
こいつを、C++から使おうってのが今回の目的です。
-- hoge.lua function get_Hoge() local hoge = Hoge() return hoge end class 'Hoge' function Hoge:__init() print("Hoge construct") end function Hoge:print(msg) print(msg) end
#include <lua.hpp> #include <luabind/luabind.hpp> int main() { lua_State* L = luaL_newstate(); luaL_openlibs(L); luabind::open(L); if( luaL_loadfile(L,"./hoge.lua") == 0 ) { lua_pcall(L,0,0,0); luabind::object const obj = luabind::call_function<::luabind::object>(L,"get_Hoge"); assert(luabind::type(obj) == LUA_TUSERDATA); luabind::call_function<void>(obj["print"],tbl,"hoge"); luabind::call_function<void>(obj["print"],tbl,"piyo"); } }
実行結果 Hoge construct hoge piyo
luabindで使えるようになったclassは、LUA_TUSEDATAとして扱われます。
classの関数や変数にアクセスするときは、擬似クラス(table)の時と同じようにoperator[]でアクセスできます。