mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2025-07-02 15:55:30 +00:00
Fully working lua_Register
This commit is contained in:
parent
2cfb27820a
commit
2be4b8fd91
@ -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);
|
||||
|
@ -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;
|
||||
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user