usertypes.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. {"test", 1337}
  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. "print('test', p.test)"
  59. );
  60. // Invoke the attached script
  61. if (lua_pcall(state, 0, LUA_MULTRET, 0) != 0) {
  62. const char* error_msg = lua_tostring(state, -1);
  63. std::cerr << "An error occured: " << error_msg << std::endl;
  64. lua_close(state);
  65. return 1;
  66. } else {
  67. lua_close(state);
  68. return 0;
  69. }
  70. }