usertypes.cpp 1.7 KB

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