usertypes.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. int main() {
  22. lua_State* state = luaL_newstate();
  23. luaL_openlibs(state);
  24. // Register our user type.
  25. // This function also registers a garbage-collector hook and a string representation function.
  26. // Both can be overwritten using the third parameter, which lets you add custom meta methods.
  27. luwra::registerUserType<Point (double, double)>(
  28. state,
  29. // Constructor name
  30. "Point",
  31. // Methods which shall be availabe in the Lua user data, need to be declared here
  32. {
  33. LUWRA_MEMBER(Point, scale),
  34. LUWRA_MEMBER(Point, x),
  35. LUWRA_MEMBER(Point, y),
  36. {"magicNumber", 1337},
  37. {"magicString", "Hello World"}
  38. },
  39. // Meta methods may be registered aswell
  40. {
  41. LUWRA_MEMBER(Point, __tostring)
  42. }
  43. );
  44. // Load Lua code
  45. luaL_loadstring(
  46. state,
  47. // Instantiate type
  48. "local p = Point(13, 37)\n"
  49. "print('p =', p)\n"
  50. // Invoke 'scale' method
  51. "p:scale(2)\n"
  52. "print('p =', p)\n"
  53. // Access 'x' and 'y' property
  54. "print('p.x =', p:x())\n"
  55. "print('p.y =', p:y())\n"
  56. // Modify 'x' property
  57. "p:x(10)\n"
  58. "print('p.x =', p:x())\n"
  59. "print('magicNumber', p.magicNumber)\n"
  60. "print('magicString', p.magicString)"
  61. );
  62. // Invoke the attached script
  63. if (lua_pcall(state, 0, LUA_MULTRET, 0) != 0) {
  64. const char* error_msg = lua_tostring(state, -1);
  65. std::cerr << "An error occured: " << error_msg << std::endl;
  66. lua_close(state);
  67. return 1;
  68. } else {
  69. lua_close(state);
  70. return 0;
  71. }
  72. }