Created
February 18, 2015 06:19
-
-
Save yorung/dcc4a78e346480dfd333 to your computer and use it in GitHub Desktop.
bind MyClass to Lua
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> | |
extern lua_State *L; | |
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; } | |
void BindMyClass() | |
{ | |
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 }, | |
}; | |
BindClass(L, myClassName, methods, [](lua_State* L) { new (lua_newuserdata(L, sizeof(MyClass))) MyClass; return 1; }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment