You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 regels
1.5 KiB

  1. #include "LuaComponent.h"
  2. LuaComponent::LuaComponent() {
  3. this->m_Env = nullptr;
  4. this->m_FileName = "";
  5. }
  6. LuaComponent::LuaComponent(const std::string& fileName, sol::state* state) {
  7. this->m_FileName = fileName;
  8. this->state = state;
  9. }
  10. LuaComponent::~LuaComponent() {
  11. if (m_Env) {
  12. sol::protected_function releaseFunc = m_Env["OnRelease"];
  13. if (releaseFunc.valid()) {
  14. releaseFunc.call();
  15. }
  16. m_Env.clear();
  17. m_Env = sol::lua_nil;
  18. }
  19. }
  20. void LuaComponent::Init() {
  21. LoadScript(m_FileName);
  22. OnInit();
  23. }
  24. void LuaComponent::OnInit() {
  25. if (m_Env) {
  26. sol::protected_function initFunc = m_Env["OnInit"];
  27. if (initFunc.valid()) {
  28. initFunc.call();
  29. }
  30. }
  31. }
  32. void LuaComponent::LoadScript(const std::string& fileName) {
  33. m_FileName = fileName;
  34. //m_Env = std::make_unique<sol::environment>(sol::environment(*state, sol::create, state->globals())).get();
  35. m_Env = sol::environment(*state, sol::create, state->globals());
  36. sol::load_result error = state->load_file(fileName);
  37. if (error.status() == sol::load_status::ok) {
  38. try {
  39. auto func_result = state->safe_script_file(fileName, m_Env);
  40. if (!func_result.valid()) {
  41. sol::error err = error;
  42. std::cout << "[LUA] lua_dofile failed with error: " << err.what() << std::endl;
  43. sol::protected_function printFunc = (*(state))["PrintGameConsole"];
  44. if (printFunc.valid()) {
  45. std::string errorMessage = std::string("[LUA] failed with error: ").append(err.what());
  46. printFunc(errorMessage);
  47. }
  48. }
  49. }
  50. catch (...) {
  51. }
  52. }
  53. state->collect_garbage();
  54. }