C调lua出错,返回c层打印错误信息.

来源:互联网 发布:大数据标准化 编辑:程序博客网 时间:2024/06/05 06:46

内容如题目

lua代码如下:
file: test.lua

local cc.a = 123

c代码如下:
file: test.c

#include <stdio.h>#include "lua.h"#include "lauxlib.h"#include "lualib.h"static int traceback( lua_State *L){    const char *msg = lua_tostring(L,-1);    if (msg)    {        /*打印发生错误时的堆栈信息,msg是错误信息,附加到打印的堆栈最前端        1是指从第一层开始回溯        这个函数之后,lua_tostring(L,-1)即可获取完整的堆栈和错误信息.        */        luaL_traceback(L,L,msg,1);    }    else    {        lua_pushliteral(L,"no message");    }}int main(int argc, char ** argv){    lua_State *L = luaL_newstate();    luaL_openlibs(L);    lua_pushcfunction(L,traceback);    int r = luaL_loadfile(L,"test.lua");    if (r != LUA_OK)    {        printf("loadfile fail, result: %d\n", r);        return 0;    }    //第四个参数表示将错误信息msg传入栈1所在的函数(错误处理函数)    r = lua_pcall(L,0,0,1);    if (r != LUA_OK)        printf("call err\n%s\n", lua_tostring(L,-1));        else        printf("call succ\n");    return 0;}

complie:

gcc -o test test.c -llua -ldl -lm

run

./test

result:

call err test.lua:2: attempt to index local 'c' (a nil value)stack traceback:        test.lua:2: in main chunk

错误信息包含文件,出错行号,错误原因,调用栈.

0 0