functions.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <luwra.hpp>
  2. #include <iostream>
  3. static
  4. void my_function_1(float num, const char* str) {
  5. std::cout << "my_function_1(" << num << ", " << str << ")" << std::endl;
  6. }
  7. static
  8. std::string my_function_2() {
  9. return "World";
  10. }
  11. static
  12. int my_function_3(int a, int b) {
  13. return a + b;
  14. }
  15. int main() {
  16. lua_State* state = luaL_newstate();
  17. luaL_openlibs(state);
  18. // Register 'my_function_1'
  19. auto wrapped_1 = LUWRA_WRAP(my_function_1);
  20. luwra::setGlobal(state, "my_function_1", wrapped_1);
  21. // Register 'my_function_2'
  22. auto wrapped_2 = LUWRA_WRAP(my_function_2);
  23. luwra::setGlobal(state, "my_function_2", wrapped_2);
  24. // Register 'my_function_3'
  25. auto wrapped_3 = LUWRA_WRAP(my_function_3);
  26. luwra::setGlobal(state, "my_function_3", wrapped_3);
  27. // Load Lua code
  28. luaL_loadstring(
  29. state,
  30. // Invoke 'my_function_1'
  31. "my_function_1(1337, 'Hello')\n"
  32. // Invoke 'my_function_2'
  33. "local result2 = my_function_2()\n"
  34. "print('my_function_2() = ' .. result2)\n"
  35. // Invoke 'my_function_3'
  36. "local result3 = my_function_3(13, 37)\n"
  37. "print('my_function_3(13, 37) = ' .. result3)\n"
  38. );
  39. // Invoke the attached script
  40. if (lua_pcall(state, 0, LUA_MULTRET, 0) != 0) {
  41. const char* error_msg = lua_tostring(state, -1);
  42. std::cerr << "An error occured: " << error_msg << std::endl;
  43. lua_close(state);
  44. return 1;
  45. } else {
  46. lua_close(state);
  47. return 0;
  48. }
  49. }