usertypes.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. {"magic", luwra::MemberMap {
  38. {"number", 1337},
  39. {"string", "Hello World"}
  40. }}
  41. },
  42. // Meta methods may be registered aswell
  43. {
  44. LUWRA_MEMBER(Point, __tostring)
  45. }
  46. );
  47. // Load Lua code
  48. luaL_loadstring(
  49. state,
  50. // Instantiate type
  51. "local p = Point(13, 37)\n"
  52. "print('p =', p)\n"
  53. // Invoke 'scale' method
  54. "p:scale(2)\n"
  55. "print('p =', p)\n"
  56. // Access 'x' and 'y' property
  57. "print('p.x =', p:x())\n"
  58. "print('p.y =', p:y())\n"
  59. // Modify 'x' property
  60. "p:x(10)\n"
  61. "print('p.x =', p:x())\n"
  62. "print('magicNumber', p.magic.number)\n"
  63. "print('magicString', p.magic.string)"
  64. );
  65. // Invoke the attached script
  66. if (lua_pcall(state, 0, LUA_MULTRET, 0) != 0) {
  67. const char* error_msg = lua_tostring(state, -1);
  68. std::cerr << "An error occured: " << error_msg << std::endl;
  69. return 1;
  70. } else {
  71. return 0;
  72. }
  73. }