refactor: LuaState replaced with lua_engine

This commit is contained in:
MihailRis
2024-06-11 13:18:30 +03:00
parent 0647bc6f90
commit 90bc86408b
22 changed files with 643 additions and 675 deletions
+101
View File
@@ -0,0 +1,101 @@
#include "lua_engine.hpp"
#include "api_lua.hpp"
#include "../../../debug/Logger.hpp"
#include "../../../util/stringutil.hpp"
#include <iomanip>
#include <iostream>
static debug::Logger logger("lua-state");
static lua_State* main_thread = nullptr;
using namespace lua;
luaerror::luaerror(const std::string& message) : std::runtime_error(message) {
}
static void remove_lib_funcs(lua_State* L, const char* libname, const char* funcs[]) {
if (getglobal(L, libname)) {
for (uint i = 0; funcs[i]; i++) {
pushnil(L);
setfield(L, funcs[i], -2);
}
}
}
static void create_libs(lua_State* L) {
openlib(L, "audio", audiolib);
openlib(L, "block", blocklib);
openlib(L, "console", consolelib);
openlib(L, "core", corelib);
openlib(L, "file", filelib);
openlib(L, "gui", guilib);
openlib(L, "input", inputlib);
openlib(L, "inventory", inventorylib);
openlib(L, "item", itemlib);
openlib(L, "json", jsonlib);
openlib(L, "pack", packlib);
openlib(L, "player", playerlib);
openlib(L, "time", timelib);
openlib(L, "toml", tomllib);
openlib(L, "world", worldlib);
addfunc(L, "print", lua::wrap<l_print>);
}
void lua::initialize() {
logger.info() << LUA_VERSION;
logger.info() << LUAJIT_VERSION;
auto L = luaL_newstate();
if (L == nullptr) {
throw luaerror("could not to initialize Lua");
}
main_thread = L;
// Allowed standard libraries
luaopen_base(L);
luaopen_math(L);
luaopen_string(L);
luaopen_table(L);
luaopen_debug(L);
luaopen_jit(L);
luaopen_bit(L);
luaopen_os(L);
const char* removed_os[] {
"execute",
"exit",
"remove",
"rename",
"setlocale",
"tmpname",
nullptr
};
remove_lib_funcs(L, "os", removed_os);
create_libs(L);
pushglobals(L);
setglobal(L, env_name(0));
createtable(L, 0, 0);
setglobal(L, LAMBDAS_TABLE);
}
void lua::finalize() {
lua_close(main_thread);
}
bool lua::emit_event(lua_State* L, const std::string &name, std::function<int(lua_State*)> args) {
getglobal(L, "events");
getfield(L, "emit");
pushstring(L, name);
call_nothrow(L, args(L) + 1);
bool result = toboolean(L, -1);
pop(L, 2);
return result;
}
lua_State* lua::get_main_thread() {
return main_thread;
}