Fully working lua_Register

This commit is contained in:
Anonymous-275 2021-06-27 14:28:16 +03:00 committed by Lion Kortlepel
parent 2cfb27820a
commit 2be4b8fd91
No known key found for this signature in database
GPG Key ID: 4322FF2B4C71259B
3 changed files with 21 additions and 22 deletions

View File

@ -4,10 +4,11 @@
#include "IThreaded.h"
#include "TLuaFile.h"
#include "TServer.h"
#include <optional>
#include <lua.hpp>
#include <memory>
#include <optional>
#include <set>
#include <unordered_map>
class TLuaEngine : public IThreaded {
public:
@ -25,6 +26,7 @@ public:
std::optional<std::reference_wrapper<TLuaFile>> GetScript(lua_State* L);
static std::unordered_map<std::string, lua_State*> mGlobals;
private:
void FolderList(const std::string& Path, bool HotSwap);
void RegisterFiles(const fs::path& Path, bool HotSwap);

View File

@ -6,6 +6,8 @@
namespace fs = std::filesystem;
std::unordered_map<std::string, lua_State*> TLuaEngine::mGlobals;
// necessary as lua relies on global state
TLuaEngine* TheEngine;

View File

@ -670,38 +670,33 @@ int lua_TempFix(lua_State* L) {
return 1;
}
template <int ID>
struct CFunctionPointer {
std::function<int(lua_State*)> 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);
}
}