为什么此代码段遇到分段错误?
luaL_dostring(L, "print('this is a test')");
printf("%s\n", lua_tostring(L, -1));
这是错误消息和回溯:
程序收到信号SIGSEGV,分段故障。../sysdeps/x86_64/strlen.S上的strlen():106 106 ../sysdeps/x86_64/strlen.S:没有这样的文件或目录。
你执行的块不返回任何内容。假设你在调用时栈为空,则在调用luaL_dostring
后它保持不变。这意味着当你调用时lua_tostring(L, -1)
,你针对一个空堆栈调用它,因此遇到了SEGV:
lua_State * L = luaL_newstate();
luaL_openlibs(L);
// stack is empty
luaL_dostring(L, "print('this is a test')");
// stack is still empty
printf("%s\n", lua_tostring(L, -1)); // segmentation fault
为了进行比较,你可以尝试:
luaL_dostring(L, "print('this is a test') return 'another string'");
printf("%s\n", lua_tostring(L, -1)); // prints: another string
为防止此类错误,请始终检查要使用的值:
luaL_dostring(L, "print('this is a test')");
if (lua_isstring(L, -1))
printf("%s\n", lua_tostring(L, -1)); // OK, line is not executed
你还可以检查的返回值lua_tolstring
:
const char * value = lua_tostring(L, -1);
if (NULL != value)
printf("%s\n", value); // Also OK
非常感谢。输出消息(即“ this is a test”)从未被压入堆栈(调用“ print('this is a test')”)时,它只是通过
fwrite()
(invoke bylua_writeline()
)函数打印到标准输出。我对吗?@John,是的,差不多,在那张纸上/
luaB_print
根本没有压入任何东西。尝试:type(print("whatever"))
并与进行比较type(nil)
。我不了解比较
type(print("whatever"))
和的目的type(nil)
。我在调用时收到错误消息。这type(print("whatever"))
是输出和错误消息:“> type(print(” whatever“))不管什么stdin:1:错误的参数#1到'type'(期望的值)堆栈回溯:[C] :在函数'type'中stdin:1:在主块[C]中:在?”@ John,Point是为了说明行为在返回
nil
和什么都不返回之间是不同的。值得记住的是,print
它不会返回任何东西,因为在某些非常罕见的情况下,它可能会引起问题。从Lua角度来看,这种情况并不经常发生,nil
几乎无处不在,并且可以tostring
处理所有类型,但是当您使用C API时,您可能会一yourself不振。