usertypes.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. register_user_type<Point>(
  30. state,
  31. // Methods which shall be availabe in the Lua user data, need to be declared here
  32. {
  33. {"scale", wrap_method<Point, void(double), &Point::scale>},
  34. {"x", wrap_property<Point, double, &Point::x>},
  35. {"y", wrap_property<Point, double, &Point::y>}
  36. },
  37. // Meta methods may be registered aswell
  38. {
  39. {"__tostring", wrap_method<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. push(state, wrap_constructor<Point, double, double>);
  46. lua_setglobal(state, "Point");
  47. // Invoke the attached script
  48. if (luaL_loadfile(state, "usertypes.lua") != 0 || lua_pcall(state, 0, LUA_MULTRET, 0) != 0) {
  49. const char* error_msg = lua_tostring(state, -1);
  50. std::cerr << "An error occured: " << error_msg << std::endl;
  51. lua_close(state);
  52. return 1;
  53. } else {
  54. lua_close(state);
  55. return 0;
  56. }
  57. }