Created
February 17, 2015 15:25
-
-
Save yorung/fe67b99946460bc40cb6 to your computer and use it in GitHub Desktop.
binding MyClass by using lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <new> | |
class MyClass | |
{ | |
public: | |
MyClass() | |
{ | |
value = 0; | |
puts("MyClass::MyClass called"); | |
} | |
~MyClass() | |
{ | |
puts("MyClass::~MyClass called"); | |
} | |
int value; | |
}; | |
static const char* myClassName = "MyClass"; | |
#define GET_MYCLASS \ | |
MyClass* p = (MyClass*)luaL_checkudata(L, 1, myClassName); \ | |
if (!p) { return 0; } | |
static int MyClassNew(lua_State *L) | |
{ | |
MyClass* p = new (lua_newuserdata(L, sizeof(MyClass))) MyClass; | |
luaL_getmetatable(L, myClassName); | |
lua_setmetatable(L, -2); | |
return 1; | |
} | |
void BindMyClass() | |
{ | |
int r = luaL_newmetatable(L, myClassName); | |
assert(r); | |
lua_pushstring(L, "__index"); | |
lua_pushvalue(L, 1); | |
lua_settable(L, -3); | |
static struct luaL_Reg methods[] = | |
{ | |
{ "__gc", [](lua_State* L) { GET_MYCLASS p->~MyClass(); return 0; } }, | |
{ "SetValue", [](lua_State* L) { GET_MYCLASS p->value = (int)lua_tointeger(L, -1); return 0; } }, | |
{ "GetValue", [](lua_State* L) { GET_MYCLASS lua_pushinteger(L, p->value); return 1; } }, | |
{ nullptr, nullptr }, | |
}; | |
luaL_setfuncs(L, methods, 0); | |
lua_pop(L, 1); | |
lua_register(L, "MyClass", MyClassNew); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment