functions.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. luwra::StateWrapper state;
  17. state.loadStandardLibrary();
  18. // Register 'my_function_1'
  19. auto wrapped_1 = LUWRA_WRAP(my_function_1);
  20. state.set("my_function_1", wrapped_1);
  21. // Register 'my_function_2'
  22. auto wrapped_2 = LUWRA_WRAP(my_function_2);
  23. state.set("my_function_2", wrapped_2);
  24. // Register 'my_function_3'
  25. auto wrapped_3 = LUWRA_WRAP(my_function_3);
  26. state.set("my_function_3", wrapped_3);
  27. // Load Lua code
  28. int ret = state.runString(
  29. // Invoke 'my_function_1'
  30. "my_function_1(1337, 'Hello')\n"
  31. // Invoke 'my_function_2'
  32. "local result2 = my_function_2()\n"
  33. "print('my_function_2() = ' .. result2)\n"
  34. // Invoke 'my_function_3'
  35. "local result3 = my_function_3(13, 37)\n"
  36. "print('my_function_3(13, 37) = ' .. result3)\n"
  37. );
  38. // Invoke the attached script
  39. if (ret != LUA_OK) {
  40. std::cerr << "An error occured: " << lua_tostring(state, -1) << std::endl;
  41. return 1;
  42. }
  43. return 0;
  44. }