usertypes.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include <lua.hpp>
  2. #include <luwra.hpp>
  3. #include <iostream>
  4. struct Point {
  5. double x, y;
  6. Point(double x, double y):
  7. x(x), y(y)
  8. {
  9. std::cout << "Construct Point(" << x << ", " << y << ")" << std::endl;
  10. }
  11. ~Point() {
  12. std::cout << "Destruct Point(" << x << ", " << y << ")" << std::endl;
  13. }
  14. void scale(double f) {
  15. x *= f;
  16. y *= f;
  17. }
  18. std::string toString() {
  19. return "<Point(" + std::to_string(x) + ", " + std::to_string(y) + ")>";
  20. }
  21. };
  22. int main() {
  23. lua_State* state = luaL_newstate();
  24. luaL_openlibs(state);
  25. // Register our user type.
  26. // This function also registers a garbage-collector hook and a string representation function.
  27. // Both can be overwritten using the third parameter, which lets you add custom meta methods.
  28. luwra::register_user_type<Point>(
  29. state,
  30. // Methods which shall be availabe in the Lua user data, need to be declared here
  31. {
  32. {"scale", luwra::wrap_method<Point, void(double), &Point::scale>},
  33. {"x", luwra::wrap_property<Point, double, &Point::x>},
  34. {"y", luwra::wrap_property<Point, double, &Point::y>}
  35. },
  36. // Meta methods may be registered aswell
  37. {
  38. {"__tostring", luwra::wrap_method<Point, std::string(), &Point::toString>}
  39. }
  40. );
  41. // What's left, is registering a constructor for our type.
  42. // We have to specify which parameters our constructor takes, because there might be more than
  43. // one constructor to deal with.
  44. luwra::push(state, luwra::wrap_constructor<Point, double, double>);
  45. lua_setglobal(state, "Point");
  46. // Invoke the attached script
  47. if (luaL_loadfile(state, "usertypes.lua") != 0 || lua_pcall(state, 0, LUA_MULTRET, 0) != 0) {
  48. const char* error_msg = lua_tostring(state, -1);
  49. std::cerr << "An error occured: " << error_msg << std::endl;
  50. lua_close(state);
  51. return 1;
  52. } else {
  53. lua_close(state);
  54. return 0;
  55. }
  56. }