96 lines
1.7 KiB
C++
96 lines
1.7 KiB
C++
#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_err("lua 解析失败[{}]:\n{}", lua_tostring(L, -1), str);
|
||
return false;
|
||
}
|
||
ret = lua_pcall(L, 0, 0, 0);
|
||
if (ret)
|
||
{
|
||
log_err("lua 执行失败[{}]:\n{}", lua_tostring(L, -1), str);
|
||
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_err("lua 解析(加载)失败[{}]:{}", path_name, lua_tostring(L, -1));
|
||
return false;
|
||
}
|
||
ret = lua_pcall(L, 0, 0, 0);
|
||
if (ret)
|
||
{
|
||
log_err("lua 执行失败[{}]:{}", path_name, lua_tostring(L, -1));
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
bool LuaScript::ExcuteFunction(luabridge::LuaRef func)
|
||
{
|
||
if (!func)
|
||
{
|
||
log_err0("lua 执行函数失败:为空");
|
||
return false;
|
||
}/*
|
||
try
|
||
{
|
||
func();
|
||
}
|
||
catch (const luabridge::LuaException& e)
|
||
{
|
||
log_err("lua 执行函数失败:{}", e.what());
|
||
return false;
|
||
}*/
|
||
auto handler = [](lua_State* L) -> int {
|
||
// Augment the error message with a traceback
|
||
luaL_traceback(L, L, lua_tostring(L, 1), 1);
|
||
return 1;
|
||
};
|
||
|
||
auto result = func.callWithHandler(handler);
|
||
if (!result)
|
||
{
|
||
log_err("lua 执行函数失败:{}", result.message());
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
void LuaScript::RegisterAll()
|
||
{
|
||
lua_register_all(L);
|
||
}
|
||
|
||
} |