methods.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include <lua.hpp>
  2. #include <luwra.hpp>
  3. #include <iostream>
  4. using namespace luwra;
  5. struct Point {
  6. double x, y;
  7. Point(double x, double y):
  8. x(x), y(y)
  9. {
  10. std::cout << "Construct Point(" << x << ", " << y << ")" << std::endl;
  11. }
  12. ~Point() {
  13. std::cout << "Destruct Point(" << x << ", " << y << ")" << std::endl;
  14. }
  15. void scale(double f) {
  16. x *= f;
  17. y *= f;
  18. }
  19. std::string toString() {
  20. return "<Point(" + std::to_string(x) + ", " + std::to_string(y) + ")>";
  21. }
  22. };
  23. int main() {
  24. lua_State* state = luaL_newstate();
  25. luaL_openlibs(state);
  26. // Register our user type.
  27. // This function also registers a garbage-collector hook and a string representation function.
  28. // Both can be overwritten using the third parameter, which lets you add custom meta methods.
  29. RegisterUserType<Point>(
  30. state,
  31. // Methods which shall be availabe in the Lua user data, need to be declared here
  32. {
  33. {"scale", WrapMethod<Point, void(double), &Point::scale>},
  34. },
  35. // Meta methods may be registered aswell
  36. {
  37. {"__tostring", WrapMethod<Point, std::string(), &Point::toString>}
  38. }
  39. );
  40. // What's left, is registering a constructor for our type.
  41. // We have to specify which parameters our constructor takes, because there might be more than
  42. // one constructor to deal with.
  43. auto wrapped_ctor = WrapConstructor<Point, double, double>;
  44. lua_pushcfunction(state, wrapped_ctor);
  45. lua_setglobal(state, "Point");
  46. // Invoke the attached script
  47. if (luaL_loadfile(state, "methods.lua") != 0 || lua_pcall(state, 0, LUA_MULTRET, 0) != 0) {
  48. const char* error_msg = lua_tostring(state, -1);
  49. std::cerr << "An error occured: " << error_msg << std::endl;
  50. lua_close(state);
  51. return 1;
  52. } else {
  53. lua_close(state);
  54. return 0;
  55. }
  56. }