functions.cpp 1.3 KB

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