Files
csgo2_tiny_server_plugin_sy…/csgo2/script_engine.cpp

82 lines
2.2 KiB
C++
Raw Normal View History

2023-10-02 18:04:54 +08:00
#include "script_engine.h"
namespace ScriptEngine {
std::string luaPath;
2023-10-03 00:25:23 +08:00
std::map<std::string, lua_State*> pluginEnvs;
std::shared_mutex mutex_pluginEnvs;
auto callFunction(lua_State* luaVm, const char* funcName) -> int {
2023-10-02 18:04:54 +08:00
lua_getglobal(luaVm, funcName);
2023-10-03 00:25:23 +08:00
auto result = 0;
do {
if (lua_type(luaVm, -1) == LUA_TNIL) {
printf("lua_getglobal :%s\n\n", lua_tostring(luaVm, -1));
result = 0;
break;
}
if (!lua_isfunction(luaVm, -1)) {
printf("lua_isfunction_err:%s\n\n", lua_tostring(luaVm, -1));
result = 0;
break;
}
if (lua_pcall(luaVm, 0, 1, 0)) {
printf("lua_pcall_err:%s\n\n", lua_tostring(luaVm, -1));
result = 0;
break;
}
const auto result = lua_toboolean(luaVm, 1);
} while (false);
2023-10-02 18:04:54 +08:00
lua_pop(luaVm, 1);
return result;
}
2023-10-03 00:25:23 +08:00
2023-10-02 18:04:54 +08:00
auto initLuaScripts() -> void {
2023-10-03 00:25:23 +08:00
auto [dirPaths, dirNames] = Tools::GetDirs(luaPath);
if (dirPaths.size() == 0) {
2023-10-02 18:04:54 +08:00
LOG("no lua file in %s\n", luaPath.c_str());
2023-10-03 00:25:23 +08:00
return;
2023-10-02 18:04:54 +08:00
}
2023-10-03 00:25:23 +08:00
std::unique_lock lock(mutex_pluginEnvs);
for (size_t i = 0; i < dirPaths.size(); i++) {
std::string dirPath = dirPaths[i];
std::string dirName = dirNames[i];
lua_State* L = luaL_newstate();
ScriptApis::initFunciton(L);
luaL_openlibs(L);
pluginEnvs[dirName] = L;
std::string file = dirPath + "\\main.lua";
if (std::filesystem::exists(file) == false) {
continue;
}
LOG("execute: %s\n", file.c_str());
if (luaL_dofile(L, file.c_str())) {
LOG("dofile_err:%s\n\n", lua_tostring(L, -1));
continue;
2023-10-02 18:04:54 +08:00
}
2023-10-03 00:25:23 +08:00
callFunction(L, "Main");
2023-10-02 18:04:54 +08:00
}
2023-10-03 00:25:23 +08:00
}
2023-10-02 18:04:54 +08:00
2023-10-03 00:25:23 +08:00
auto releaseLuaScripts() -> void {
std::unique_lock lock(mutex_pluginEnvs);
for (auto& pair : pluginEnvs) {
lua_close(pair.second);
}
pluginEnvs.clear();
2023-10-02 18:04:54 +08:00
}
2023-10-03 00:25:23 +08:00
auto reloadLuaScripts() -> void {
releaseLuaScripts();
2023-10-02 18:04:54 +08:00
initLuaScripts();
}
2023-10-03 00:25:23 +08:00
auto Init() -> void {
// luaPath = Tools::GetExePath() + "\\huoji_scripts\\";
luaPath = "F:\\source2\\huoji_scripts\\";
initLuaScripts();
2023-10-02 18:04:54 +08:00
}
2023-10-03 00:25:23 +08:00
} // namespace ScriptEngine