usertypes.cpp 1.7 KB

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