|
- #include "LuaComponent.h"
-
- LuaComponent::LuaComponent() {
- this->m_Env = nullptr;
- this->m_FileName = "";
- }
-
- LuaComponent::LuaComponent(const std::string& fileName, sol::state* state) {
- this->m_FileName = fileName;
- this->state = state;
- }
- LuaComponent::~LuaComponent() {
- if (m_Env) {
- sol::protected_function releaseFunc = m_Env["OnRelease"];
- if (releaseFunc.valid()) {
- releaseFunc.call();
- }
- m_Env.clear();
- m_Env = sol::lua_nil;
- }
- }
-
- void LuaComponent::Init() {
- LoadScript(m_FileName);
- OnInit();
- }
-
- void LuaComponent::OnInit() {
- if (m_Env) {
- sol::protected_function initFunc = m_Env["OnInit"];
- if (initFunc.valid()) {
- initFunc.call();
- }
- }
- }
-
- void LuaComponent::LoadScript(const std::string& fileName) {
- m_FileName = fileName;
- //m_Env = std::make_unique<sol::environment>(sol::environment(*state, sol::create, state->globals())).get();
- m_Env = sol::environment(*state, sol::create, state->globals());
- sol::load_result error = state->load_file(fileName);
-
- if (error.status() == sol::load_status::ok) {
- try {
- auto func_result = state->safe_script_file(fileName, m_Env);
- if (!func_result.valid()) {
- sol::error err = error;
- std::cout << "[LUA] lua_dofile failed with error: " << err.what() << std::endl;
- sol::protected_function printFunc = (*(state))["PrintGameConsole"];
- if (printFunc.valid()) {
- std::string errorMessage = std::string("[LUA] failed with error: ").append(err.what());
- printFunc(errorMessage);
- }
- }
- }
- catch (...) {
-
- }
- }
- state->collect_garbage();
- }
|