usertypes.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <luwra.hpp>
  2. #include <iostream>
  3. struct Point {
  4. double x, y;
  5. Point(double x, double y):
  6. x(x), y(y)
  7. {
  8. std::cout << "Construct Point(" << x << ", " << y << ")" << std::endl;
  9. }
  10. ~Point() {
  11. std::cout << "Destruct Point(" << x << ", " << y << ")" << std::endl;
  12. }
  13. void scale(double f) {
  14. x *= f;
  15. y *= f;
  16. }
  17. std::string __tostring() const {
  18. return "<Point(" + std::to_string(x) + ", " + std::to_string(y) + ")>";
  19. }
  20. };
  21. LUWRA_DEF_REGISTRY_NAME(Point, "Point")
  22. int main() {
  23. luwra::StateWrapper state;
  24. state.loadStandardLibrary();
  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. {"magicNumber", 1337},
  38. {"magicString", "Hello World"}
  39. },
  40. // Meta methods may be registered aswell
  41. {
  42. LUWRA_MEMBER(Point, __tostring)
  43. }
  44. );
  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. "print('magicNumber', p.magicNumber)\n"
  61. "print('magicString', p.magicString)"
  62. );
  63. // Invoke the attached script
  64. if (lua_pcall(state, 0, LUA_MULTRET, 0) != 0) {
  65. const char* error_msg = lua_tostring(state, -1);
  66. std::cerr << "An error occured: " << error_msg << std::endl;
  67. return 1;
  68. } else {
  69. return 0;
  70. }
  71. }