-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLPM.cpp
More file actions
89 lines (81 loc) · 2.59 KB
/
LPM.cpp
File metadata and controls
89 lines (81 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include "lua.hpp"
#include <string>
#include <vector>
#include <iostream>
#include <variant>
class LuaPluginManager {
public:
LuaPluginManager() {
luaState = luaL_newstate();
luaL_openlibs(luaState);
}
~LuaPluginManager() {
lua_close(luaState);
}
lua_State* GetLuaState() {
return luaState;
}
bool LoadPlugin(const std::string& pluginPath) {
pluginPaths.push_back(pluginPath);
return true;
}
void ExecutePlugins() {
for (const auto& pluginPath : pluginPaths) {
if (luaL_loadfile(luaState, pluginPath.c_str()) || lua_pcall(luaState, 0, 0, 0)) {
const char* errorMessage = lua_tostring(luaState, -1);
lua_pop(luaState, 1);
}
}
}
template<typename T>
T GetLuaVariable(const std::string& varName) {
lua_getglobal(luaState, varName.c_str());
if (lua_isnumber(luaState, -1)) {
if constexpr (std::is_same_v<T, int>) {
if (lua_isinteger(luaState, -1)) {
T value = static_cast<T>(lua_tointeger(luaState, -1));
lua_pop(luaState, 1);
return value;
}
}
if constexpr (std::is_same_v<T, double>) {
T value = static_cast<T>(lua_tonumber(luaState, -1));
lua_pop(luaState, 1);
return value;
}
}
else if (lua_isstring(luaState, -1)) {
if constexpr (std::is_same_v<T, std::string>) {
const char* str = lua_tostring(luaState, -1);
lua_pop(luaState, 1);
return std::string(str);
}
}
lua_pop(luaState, 1);
return T();
}
template<typename T>
void SetLuaVariable(const std::string& varName, T value) {
lua_pushnumber(luaState, static_cast<double>(value));
lua_setglobal(luaState, varName.c_str());
}
template<typename Func>
void RegisterFunction(const std::string& funcName, Func* func) {
lua_pushlightuserdata(luaState, (void*)func);
lua_pushcclosure(luaState, &LuaFunctionWrapper<Func>, 1);
lua_setglobal(luaState, funcName.c_str());
}
private:
lua_State* luaState;
std::vector<std::string> pluginPaths;
template<typename Func>
static int LuaFunctionWrapper(lua_State* L) {
Func* func = (Func*)lua_touserdata(L, lua_upvalueindex(1));
if (func) {
int result = (*func)(L);
lua_pushnumber(L, result);
return 1;
}
return 0;
}
};