usertypes.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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() const {
  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::registerUserType<Point>(
  29. state,
  30. // Methods which shall be availabe in the Lua user data, need to be declared here
  31. {
  32. LUWRA_MEMBER(Point, scale),
  33. LUWRA_MEMBER(Point, x),
  34. LUWRA_MEMBER(Point, y)
  35. },
  36. // Meta methods may be registered aswell
  37. {
  38. LUWRA_MEMBER(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::setGlobal(state, "Point", LUWRA_WRAP_CONSTRUCTOR(Point, double, double));
  45. // Load Lua code
  46. luaL_loadstring(
  47. state,
  48. // Instantiate type
  49. "local p = Point(13, 37)\n"
  50. "print('p =', p)\n"
  51. // Invoke 'scale' method
  52. "p:scale(2)\n"
  53. "print('p =', p)\n"
  54. // Access 'x' and 'y' property
  55. "print('p.x =', p:x())\n"
  56. "print('p.y =', p:y())\n"
  57. // Modify 'x' property
  58. "p:x(10)\n"
  59. "print('p.x =', p:x())\n"
  60. );
  61. // Invoke the attached script
  62. if (lua_pcall(state, 0, LUA_MULTRET, 0) != 0) {
  63. const char* error_msg = lua_tostring(state, -1);
  64. std::cerr << "An error occured: " << error_msg << std::endl;
  65. lua_close(state);
  66. return 1;
  67. } else {
  68. lua_close(state);
  69. return 0;
  70. }
  71. }