#include "util_lua.h"
// 调试
// ---------------------------------------------------------------------------
static int traceback(lua_State* L)
{
const char* msg = lua_tostring(L, 1);
if (msg == NULL)
{
if (luaL_callmeta(L, 1, "__tostring") && lua_type(L, -1) == LUA_TSTRING)
return 1;
else
msg = lua_pushfstring(L, "(error object is a %s value)", luaL_typename(L, 1));
}
luaL_traceback(L, L, msg, 1);
return 1;
}
// 调用lua函数
// ---------------------------------------------------------------------------
static int call(lua_State *L, int n, int r)
{
int err = lua_pcall(L, n, r, 1);
switch (err)
{
case LUA_OK:
break;
case LUA_YIELD:
printf("!LUA_YIELD : %s\n", lua_tostring(L, -1));
break;
case LUA_ERRRUN:
printf("!LUA_ERRRUN : %s\n", lua_tostring(L, -1));
break;
case LUA_ERRSYNTAX:
printf("!LUA_ERRSYNTAX : %s\n", lua_tostring(L, -1));
break;
case LUA_ERRMEM:
printf("!LUA_ERRMEM : %s\n", lua_tostring(L, -1));
break;
case LUA_ERRERR:
printf("!LUA_ERRERR : %s\n", lua_tostring(L, -1));
break;
default:
printf("!Unknown Lua error: %d\n", err);
break;
}
return err;
}
// ---------------------------------------------------------------------------
void lua_load_script(lua_State* L, const char* script_path)
{
// 加载脚本和执行脚本
lua_settop(L, 0);
int status = luaL_loadfile(L, script_path);
if (status == LUA_OK)
{
status = call(L, 0, 1);
}
if (status != LUA_OK || !lua_istable(L, -1))
{
lua_newtable(L);
}
lua_setfield(L, LUA_REGISTRYINDEX, "fw");
// 添加trace
lua_settop(L, 0);
lua_pushcfunction(L, traceback);
lua_getfield(L, LUA_REGISTRYINDEX, "fw");
}
// 无参调用
// ---------------------------------------------------------------------------
bool lua_call_vv(lua_State* L, const char* func)
{
lua_getfield(L, 2, func);
if (!lua_isfunction(L, -1))
{
printf("not found function export.%s\n", func);
lua_settop(L, 2);
return false;
}
call(L, 0, 0);
lua_settop(L, 2);
return true;
}
// ---------------------------------------------------------------------------
bool lua_call_vi2(lua_State* L, const char* func, int i1, int i2)
{
lua_getfield(L, 2, func);
if (!lua_isfunction(L, -1))
{
printf("not found function export.%s\n", func);
lua_settop(L, 2);
return false;
}
lua_pushinteger(L, i1);
lua_pushinteger(L, i2);
call(L, 2, 0);
lua_settop(L, 2);
return true;
}
标签:return,十万个,LUA,int,lua,tostring,printf,交互 From: https://www.cnblogs.com/kehuadong/p/18305332