將 C++ 動態創建的對象實例註冊到 Lua 虛擬機,使其在 Lua 中成為一等公民,支持運算符重載與方法調用。
對象在運行時創建,需確保 C++ 側生命周期與 Lua 側同步。推薦使用智能指針(`shared_ptr`)存儲於 userdata,配合自定義 deleter,實現雙向引用計數管理。
// 註冊類元表
luaL_newmetatable(L, "MyClass");
lua_pushcfunction(L, l_add); lua_setfield(L, -2, "__add");
// ... 其他運算符
lua_pushcfunction(L, l_gc); lua_setfield(L, -2, "__gc");
// 方法表
lua_newtable(L);
lua_pushcfunction(L, l_method); lua_setfield(L, -2, "method");
lua_setfield(L, -2, "__index");
// 創建對象實例
T** ud = (T**)lua_newuserdata(L, sizeof(T*));
*ud = new T(args);
luaL_setmetatable(L, "MyClass");