尝试在lua 5.4中编写以下代码
static int foreach(lua_State *L){
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checktype(L, 2, LUA_TFUNCTION);
lua_getglobal(L, "print");
if (!lua_rawequal(L, -1, 2)) {
lua_pop(L, 1);
return luaL_error(L, "Second argument must be the 'print' function");
}
lua_pop(L, 1);
lua_yield(L, 0);
lua_pushnil(L);
while (lua_next(L, 1) != 0) {
lua_pushvalue(L, 2); // push print
lua_pushvalue(L, -3); // push key
lua_pushvalue(L, -3); // push value
lua_call(L, 2, 0);
lua_pop(L, 1);
}
return 0;
}
static int resume_func_continuation(lua_State * L, int status, lua_KContext ctx) {
int res;
(void) ctx;
if (status != LUA_YIELD) {
luaL_error(L, "Thread was not yielding. %s", lua_tostring(L, -1));
exit(1);
}
lua_getglobal(L, "foreach");
char *lua_Code = "foreach({x = 10, y = 20}; print)";
res = luaL_dostring(L, lua_Code);
if (res != LUA_OK) {
luaL_error(L, "Error running lua_Code. %s\n", lua_tostring(L, -1));
}
lua_close(L);
exit(0);
}
int main(void) {
int res;
lua_State *L = luaL_newstate();
if (L == NULL) luaL_error(L, "Error creating new state. %s\n", lua_tostring(L, -1));
luaL_openlibs(L);
lua_State *L1 = lua_newthread(L);
if (L1 == NULL) {
luaL_error(L, "Error, cannot create new thread. %s", lua_tostring(L, -1));
exit(1);
}
lua_pushcfunction(L1, foreach);
lua_setglobal(L1, "foreach");
res = lua_pcallk(L1, 0, 0, 0, 0, resume_func_continuation);
if (res != LUA_OK) {
luaL_error(L, "Error calling foreach function. %s", lua_tostring(L, -1));
exit(1);
}
//lua_closethread(L1, L);
return 0;
}
我需要创建一个新线程,pcallk lua cfunction,cfunction将yield,最后关闭线程,我在pcallk()上遇到分段错误,并且从lua 5.4开始无法识别closethread。有什么建议吗?我需要遵循这些步骤而不是其他......
lua_setglobal
会将c函数从堆栈中弹出,导致lua_pcallk
调用无效位置,您需要在设置全局之前复制c函数。
lua_pushcfunction(L1, foreach);
lua_pushvalue(L1, -1);
lua_setglobal(L1, "foreach");
res = lua_pcallk(L1, 0, 0, 0, 0, resume_func_continuation);