static const luaL_Reg Vector3Table[] = { {"new", LuaLibs_Vector3New}, {NULL, NULL} }; void luaL_register(lua_State* L, const char* libname, const luaL_Reg* l) { lua_newtable(L); luaL_setfuncs(L, l, 0); lua_setglobal(L, libname); } // Start from here // Called from Lua_Init void Lua_SetupLibs( void ) { luaL_openlibs(L); // Setup our custom functions here luaL_register(L, "Vector3", Vector3Table); } int LuaLibs_Vector3New(lua_State* L) { vec3_t vec; if (lua_gettop(L) != 3) { luaL_error(L, "Expected 3 arguments for Vector3: x, y, z"); return 0; // error } vec[0] = luaL_checknumber(L, 1); // x vec[1] = luaL_checknumber(L, 2); // y vec[2] = luaL_checknumber(L, 3); // z LuaLibs_Vec3ToLuaVector3(L, vec); return 2; // return the new vector table } void LuaLibs_Vec3ToLuaVector3(lua_State* L, vec3_t vec) { lua_newtable(L); // create a new table for the vector lua_pushnumber(L, vec[0]); // x lua_setfield(L, -2, "x"); lua_pushnumber(L, vec[1]); // y lua_setfield(L, -2, "y"); lua_pushnumber(L, vec[2]); // z lua_setfield(L, -2, "z"); // Metatable for vector operations luaL_newmetatable(L, "Vector3"); // create a new metatable lua_pushcfunction(L, LuaLibs_Vector3Add); // add the add function lua_setfield(L, -2, "__add"); // set the __add metamethod lua_pushcfunction(L, LuaLibs_Vector3Sub); lua_setfield(L, -2, "__sub"); // set the __sub metamethod lua_pushcfunction(L, LuaLibs_Vector3ToString); lua_setfield(L, -2, "__tostring"); // set the __tostring metamethod lua_setmetatable(L, -2); // set the metatable for the vector table }