usertypes.cpp 1.8 KB

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