Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A core-dump when using lua_yield and lua_resume

Tags:

coroutine

lua

I just want to resume the func coroutine twice, yield if n==0, and return if n==1 , but it core dumps, what't wrong with it?

the "hello world" should always be left in LL's stack, I can't figure out what is wrong.

[[email protected] lua]$ ./main 
func_top=1 top=hello world
first_top=1 top_string=hello world
Segmentation fault (core dumped)
[[email protected] lua]$ cat main.c 
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

int n = 0;

int func(lua_State *L) {
    printf("func_top=%d top=%s\n", lua_gettop(L), lua_tostring(L, -1));
    if (!n) {
        ++ n;
        return lua_yield(L, 1);
    } else {
        return 1;
    }
}

int main(int argc, char* const argv[]) {
    lua_State *L = luaL_newstate();

    /* init lua library */    
    lua_pushcfunction(L, luaopen_base);
    if (lua_pcall(L, 0, 0, 0) != 0) {
        return 1;
    }
    lua_pushcfunction(L, luaopen_package);
    if (lua_pcall(L, 0, 0, 0 ) != 0) {
        return 2;
    }

    /* create the coroutine */
    lua_State *LL = lua_newthread(L);

    lua_pushcfunction(LL, func);
    lua_pushstring(LL, "hello world");

    /* first time resume */
    if (lua_resume(LL, 1) == LUA_YIELD) {
        printf("first_top=%d top_string=%s\n", lua_gettop(LL), lua_tostring(LL, -1));
        /* twice resume */
        if (lua_resume(LL, 1) == 0) {
            printf("second_top=%d top_string=%s\n", lua_gettop(LL), lua_tostring(LL, -1));
        }
    }

    lua_close(L);

    return 0;
}

it core dumps in lua5.1, but works well in lua5.2 if change lua_resume(LL, 1) to lua_resume(LL, NULL, 1).

like image 466
liangdong from baidu Avatar asked May 31 '26 05:05

liangdong from baidu


1 Answers

EDIT: I was actually totally wrong.

You cannot resume a C function.

like image 59
tprk77 Avatar answered Jun 01 '26 21:06

tprk77