#include #include #include using namespace luwra; struct Point { double x, y; Point(double x, double y): x(x), y(y) { std::cout << "Construct Point(" << x << ", " << y << ")" << std::endl; } ~Point() { std::cout << "Destruct Point(" << x << ", " << y << ")" << std::endl; } void scale(double f) { x *= f; y *= f; } std::string toString() { return ""; } }; int main() { lua_State* state = luaL_newstate(); luaL_openlibs(state); // Register our user type. // This function also registers a garbage-collector hook and a string representation function. // Both can be overwritten using the third parameter, which lets you add custom meta methods. RegisterUserType( state, // Methods which shall be availabe in the Lua user data, need to be declared here { {"scale", WrapMethod}, }, // Meta methods may be registered aswell { {"__tostring", WrapMethod} } ); // What's left, is registering a constructor for our type. // We have to specify which parameters our constructor takes, because there might be more than // one constructor to deal with. auto wrapped_ctor = WrapConstructor; lua_pushcfunction(state, wrapped_ctor); lua_setglobal(state, "Point"); // Invoke the attached script if (luaL_loadfile(state, "methods.lua") != 0 || lua_pcall(state, 0, LUA_MULTRET, 0) != 0) { const char* error_msg = lua_tostring(state, -1); std::cerr << "An error occured: " << error_msg << std::endl; lua_close(state); return 1; } else { lua_close(state); return 0; } }