Created
February 7, 2015 12:50
-
-
Save yorung/c3194c463ebc48ea1176 to your computer and use it in GitHub Desktop.
class bind 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
class MyClass | |
{ | |
public: | |
int value; | |
}; | |
static const char* myClassName = "MyClass"; | |
static int MyClassSetValue(lua_State *L) | |
{ | |
MyClass** pp = (MyClass**)luaL_checkudata(L, -2, myClassName); | |
(*pp)->value = (int)lua_tointeger(L, -1); | |
return 0; | |
} | |
static int MyClassGetValue(lua_State *L) | |
{ | |
MyClass** pp = (MyClass**)luaL_checkudata(L, -1, myClassName); | |
lua_pushinteger(L, (*pp)->value); | |
return 1; | |
} | |
static int MyClassGC(lua_State *L) | |
{ | |
MyClass** pp = (MyClass**)luaL_checkudata(L, -1, myClassName); | |
delete *pp; | |
return 0; | |
} | |
static int MyClassNew(lua_State *L) | |
{ | |
MyClass** pp = (MyClass**)lua_newuserdata(L, sizeof(MyClass*)); | |
*pp = new MyClass; | |
(*pp)->value = 0; | |
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); | |
lua_pushstring(L, "__gc"); | |
lua_pushcfunction(L, MyClassGC); | |
lua_settable(L, -3); | |
lua_pushstring(L, "SetValue"); | |
lua_pushcfunction(L, MyClassSetValue); | |
lua_settable(L, -3); | |
lua_pushstring(L, "GetValue"); | |
lua_pushcfunction(L, MyClassGetValue); | |
lua_settable(L, -3); | |
lua_pop(L, 1); | |
lua_register(L, "MyClass", MyClassNew); | |
} |
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
local obj = MyClass() | |
obj:SetValue(1234) | |
print("My value is", obj:GetValue()) |
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
My value is 1234 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment