test.h:
#ifndef __TEST_H__ #define __TEST_H__ class CTest { public: CTest(); ~CTest(); int getA(); void setA(int a); private: int m_a; }; #endif
test.cpp:
#include "test.h" CTest::CTest() { m_a = 0; } CTest::~CTest() { } int CTest::getA() { return m_a; } void CTest::setA(int a) { m_a = a; }
main.cpp:
#include "test.h" extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" #include "luaconf.h" }; static int CreateTest(lua_State* L) { CTest** ppTest = (CTest**)lua_newuserdata(L, sizeof(CTest*)); *ppTest = new CTest; luaL_getmetatable(L, "test"); lua_setmetatable(L, -2); return 1; } static int TestGetA(lua_State* L) { CTest** ppTest = (CTest**)luaL_checkudata(L, 1, "test"); luaL_argcheck(L, ppTest != NULL, 1, "invalid user data"); lua_pushnumber(L, (int)(*ppTest)->getA()); return 1; } static int TestSetA(lua_State* L) { CTest** ppTest = (CTest**)luaL_checkudata(L, 1, "test"); luaL_argcheck(L, ppTest != NULL, 1, "invalid user data"); int a = (int)lua_tointeger(L, 2); (*ppTest)->setA(a); return 0; } static int DeleteTest(lua_State* L) { CTest** ppTest = (CTest**)luaL_checkudata(L, 1, "test"); delete *ppTest; printf("test is deleted"); return 0; } static const struct luaL_Reg test_reg_f[] = { {"test", CreateTest}, {NULL, NULL}, }; static const struct luaL_Reg test_reg_mf[] = { {"TestGetA", TestGetA}, {"TestSetA", TestSetA}, {"__gc", DeleteTest}, {NULL, NULL}, }; static int testModelOpen(lua_State* L) { luaL_newlib(L, test_reg_f); return 1; } int main() { int top = 0; lua_State* L = luaL_newstate(); top = lua_gettop(L); luaopen_base(L); luaL_openlibs(L); top = lua_gettop(L); //加载模块 luaL_requiref(L, "testModel", testModelOpen, 0); top = lua_gettop(L); //创建metatable luaL_newmetatable(L, "test"); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); luaL_setfuncs(L, test_reg_mf, 0); lua_pop(L, 1); top = lua_gettop(L); int ret = luaL_dofile(L, "test.lua"); if(ret != 0) { printf("%s", lua_tostring(L, -1)); } lua_close(L); getchar(); return 1; }
test.lua:
local testModel = require("testModel"); local test1 = testModel.test(); test1:TestSetA(1); print('value is : ' .. test1:TestGetA());