methods.cpp 1.9 KB

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