Files
2026-07-17 19:22:26 +08:00

141 lines
2.7 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "dl_lua.h"
#define LUA_USE_APICHECK
#include <lua.hpp>
#include "dl_lua_register.h"
#include "io/dl_file.h"
namespace dl
{
LuaScript* g_lua;
LuaScript::LuaScript()
{
L = luaL_newstate();
luaL_openlibs(L);
}
LuaScript::~LuaScript()
{
lua_close(L);
}
bool LuaScript::DoString(std::string_view str)
{
int ret = luaL_loadstring(L, str.data());
if (ret)
{
log_warn("lua 解析失败[{}]:\n{}", lua_tostring(L, -1), str);
lua_pop(L, 1);
return false;
}
ret = lua_pcall(L, 0, 0, 0);
if (ret)
{
log_warn("lua 执行失败[{}]:\n{}", lua_tostring(L, -1), str);
lua_pop(L, 1);
return false;
}
return true;
}
bool LuaScript::DoFile(std::string_view path_name)
{
Buffer buf = File::GetBuffer(path_name);
int ret = luaL_loadbuffer(L, (const char*)buf.data(), buf.size(), path_name.data());
if (ret)
{
log_warn("lua 解析(加载)失败[{}]:{}", path_name, lua_tostring(L, -1));
lua_pop(L, 1);
return false;
}
ret = lua_pcall(L, 0, 0, 0);
if (ret)
{
log_warn("lua 执行失败:{}", lua_tostring(L, -1));
lua_pop(L, 1);
return false;
}
log_msg("执行lua脚本成功:{}", path_name);
return true;
}
bool LuaScript::DoFileEx(std::string_view path_name, LuaRef& ret_ref)
{
Buffer buf = File::GetBuffer(path_name);
int ret = luaL_loadbuffer(L, (const char*)buf.data(), buf.size(), path_name.data());
if (ret)
{
log_warn("lua 解析(加载)失败[{}]:{}", path_name, lua_tostring(L, -1));
lua_pop(L, 1);
return false;
}
ret = lua_pcall(L, 0, 1, 0);
if (ret)
{
log_warn("lua 执行失败:{}", lua_tostring(L, -1));
lua_pop(L, 1);
return false;
}
ret_ref = LuaRef::fromStack(L, -1);
lua_pop(L, 1);
log_msg("执行lua脚本成功:{}", path_name);
return true;
}
bool LuaScript::CallFunction(luabridge::LuaRef func)
{
if (!func)
{
log_warn("lua 执行函数失败:为空");
return false;
}
const char* traceback = nullptr;
auto handler = [&traceback](lua_State* L) -> int
{
const char* msg = luaL_tolstring(L, 1, nullptr);
luaL_traceback(L, L, msg, 1);
lua_pop(L, 1);
const char* tb = lua_tostring(L, -1);
traceback = tb ? tb : "Unknown Lua error";
return 1;
};
auto result = func.callWithHandler(handler);
if (!result)
{
log_warn("lua 执行函数失败:{}", traceback);
return false;
}
return true;
}
std::string LuaScript::GetRefString(LuaRef ref)
{
if (!ref)
return {};
if (ref.isCallable())
{
auto ret = ref.call<std::string>();
if (ret)
return ret.value();
}
else if (ref.isString())
{
return ref.cast<std::string>().value();
}
return {};
}
void LuaScript::RegisterAll()
{
lua_register_all(L);
}
}