functions.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include <lua.hpp>
  2. #include <luwra.hpp>
  3. #include <iostream>
  4. static
  5. void my_function_1(float num, const char* str) {
  6. std::cout << "my_function_1(" << num << ", " << str << ")" << std::endl;
  7. }
  8. static
  9. std::string my_function_2() {
  10. return "World";
  11. }
  12. static
  13. int my_function_3(int a, int b) {
  14. return a + b;
  15. }
  16. int main() {
  17. lua_State* state = luaL_newstate();
  18. luaL_openlibs(state);
  19. // Register 'my_function_1'
  20. auto wrapped_1 = luwra::wrap_function<void(float, const char*), my_function_1>;
  21. luwra::push(state, wrapped_1);
  22. lua_setglobal(state, "my_function_1");
  23. // Register 'my_function_2'
  24. auto wrapped_2 = luwra::wrap_function<std::string(), my_function_2>;
  25. luwra::push(state, wrapped_2);
  26. lua_setglobal(state, "my_function_2");
  27. // Register 'my_function_3'
  28. auto wrapped_3 = luwra::wrap_function<int(int, int), my_function_3>;
  29. luwra::push(state, wrapped_3);
  30. lua_setglobal(state, "my_function_3");
  31. // Invoke the attached script
  32. if (luaL_loadfile(state, "functions.lua") != 0 || lua_pcall(state, 0, LUA_MULTRET, 0) != 0) {
  33. const char* error_msg = lua_tostring(state, -1);
  34. std::cerr << "An error occured: " << error_msg << std::endl;
  35. lua_close(state);
  36. return 1;
  37. } else {
  38. lua_close(state);
  39. return 0;
  40. }
  41. }