diff --git a/include/TLuaEngine.h b/include/TLuaEngine.h index 9e59964..94e3189 100644 --- a/include/TLuaEngine.h +++ b/include/TLuaEngine.h @@ -4,10 +4,11 @@ #include "IThreaded.h" #include "TLuaFile.h" #include "TServer.h" +#include #include #include -#include #include +#include class TLuaEngine : public IThreaded { public: @@ -25,6 +26,7 @@ public: std::optional> GetScript(lua_State* L); + static std::unordered_map mGlobals; private: void FolderList(const std::string& Path, bool HotSwap); void RegisterFiles(const std::string& Path, bool HotSwap); diff --git a/src/TLuaEngine.cpp b/src/TLuaEngine.cpp index 87a1f7c..cd535a9 100644 --- a/src/TLuaEngine.cpp +++ b/src/TLuaEngine.cpp @@ -6,6 +6,8 @@ namespace fs = std::filesystem; +std::unordered_map TLuaEngine::mGlobals; + // necessary as lua relies on global state TLuaEngine* TheEngine; diff --git a/src/TLuaFile.cpp b/src/TLuaFile.cpp index 71f1198..49129c0 100644 --- a/src/TLuaFile.cpp +++ b/src/TLuaFile.cpp @@ -644,38 +644,33 @@ int lua_TempFix(lua_State* L) { return 1; } -template -struct CFunctionPointer { - std::function func; +int lua_Registered(lua_State* L) { - static int callback(lua_State* s) { - return instance().func(s); + lua_Debug info; + lua_getstack(L, 0, &info); + lua_getinfo(L, "n", &info); + + if(auto it = TLuaEngine::mGlobals.find(info.name); it != TLuaEngine::mGlobals.end()){ + lua_getglobal(it->second, info.name); + if (lua_isfunction(it->second, -1)) { + lua_pcall(it->second, 0, 0, 0); //TODO revisit to allow arguments and return + } + return 0; } - static CFunctionPointer& instance() { - static CFunctionPointer inst_; - return inst_; - } -}; + SendError(Engine(), L, "Cannot find global '" + std::string(info.name) + "\'"); + return 0; +} int lua_Register(lua_State* L) { if(lua_isstring(L, 1)){ std::string Name(lua_tolstring(L, 1, nullptr)); lua_getglobal(L, Name.c_str()); if (lua_isfunction(L, -1)) { + TLuaEngine::mGlobals.emplace(Name, L); for (auto& Script : Engine().LuaFiles()) { if(Script->GetState() != L){ - - CFunctionPointer<0> F; //How do we pass a value instead of a const - F.instance().func = [=](lua_State* A) { - lua_getglobal(L, Name.c_str()); - if (lua_isfunction(L, -1)) { - lua_pcall(L, 0, 0, 0); - } - return 0; - }; - - lua_register(Script->GetState(), Name.c_str(), F.callback); + lua_register(Script->GetState(), Name.c_str(), lua_Registered); } }