lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Is it possible to yield values from a hook?
I can't seem to see where the values I push are going

yield-from-hook.c:

#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

#if LUA_VERSION_NUM == 501
#define lua_resume(co, L, n) ((void)(L), lua_resume((co), (n)))
#endif

void f(lua_State *L, lua_Debug *ar) {
    (void)ar;
    lua_pushliteral(L, "from hook");
    lua_yield(L, 1);
}

int main() {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    /* create a coroutine that does some work then yields */
    lua_State *co = lua_newthread(L);
    if (luaL_loadstring(co, "print('first'); coroutine.yield('test')
print('second')")) {
        lua_xmove(co, L, 1);
        return lua_error(L);
    }
    if (lua_resume(co, L, 0) != LUA_YIELD) return 1;
    /* inspect the coroutine's stack */
    printf("YIELDED n=%d", lua_gettop(co));
    for (int i=1; i<=lua_gettop(co); i++) {
        printf("\t%s:%s", luaL_typename(co, i), lua_tolstring(co, i, NULL));
    }
    printf("\n");
    /* cool; there was the yielded 'test' */
    /* clear coroutine's stack */
    lua_settop(co, 0);

    /* give the coroutine a a debug hook that yields */
    lua_sethook(co, f, LUA_MASKCOUNT, 1);
    if (lua_resume(co, L, 0) != LUA_YIELD) return 2;
    /* the debug hook has now yielded */

    /* inspect the coroutine's stack */
    printf("YIELDED n=%d", lua_gettop(co));
    for (int j=1; i<=lua_gettop(co); i++) {
        printf("\t%s:%s", luaL_typename(co, i), lua_tolstring(co, i, NULL));
    }
    printf("\n");
    /* wait... where did 'from hook' go? */
    /* inspect the main stack... */
    printf("MAIN n=%d", lua_gettop(L));
    for (int k=1; i<=lua_gettop(L); i++) {
        printf("\t%s:%s", luaL_typename(L, i), lua_tolstring(L, i, NULL));
    }
    printf("\n");
    /* ????? */
    return 0;
}


$ gcc -Wall -Wextra -l lua yield-from-hook.c && ./a.out
first
YIELDED n=1 string:test
YIELDED n=0
MAIN n=1 thread:(null)