functions.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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(my_function_1);
  21. luwra::setGlobal(state, "my_function_1", wrapped_1);
  22. // Register 'my_function_2'
  23. auto wrapped_2 = LUWRA_WRAP(my_function_2);
  24. luwra::setGlobal(state, "my_function_2", wrapped_2);
  25. // Register 'my_function_3'
  26. auto wrapped_3 = LUWRA_WRAP(my_function_3);
  27. luwra::setGlobal(state, "my_function_3", wrapped_3);
  28. // Load Lua code
  29. luaL_loadstring(
  30. state,
  31. // Invoke 'my_function_1'
  32. "my_function_1(1337, 'Hello')\n"
  33. // Invoke 'my_function_2'
  34. "local result2 = my_function_2()\n"
  35. "print('my_function_2() = ' .. result2)\n"
  36. // Invoke 'my_function_3'
  37. "local result3 = my_function_3(13, 37)\n"
  38. "print('my_function_3(13, 37) = ' .. result3)\n"
  39. );
  40. // Invoke the attached script
  41. if (lua_pcall(state, 0, LUA_MULTRET, 0) != 0) {
  42. const char* error_msg = lua_tostring(state, -1);
  43. std::cerr << "An error occured: " << error_msg << std::endl;
  44. lua_close(state);
  45. return 1;
  46. } else {
  47. lua_close(state);
  48. return 0;
  49. }
  50. }