lua-users home
lua-l archive

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


Hello Lua mailing list,

I'm currently writing a binding to SWI-Prolog that uses coroutines to
yield results on demand instead of in one big batch.  Since I've never
used coroutines from the C side in Lua before, I decided to write a
simple test program first.  Here's what I'm trying to accomplish in Lua:

function iterate()
  coroutine.yield(1)
  coroutine.yield(2)
  coroutine.yield(3)
end

co = coroutine.create(iterate)
print(coroutine.resume(co))
print(coroutine.resume(co))
print(coroutine.resume(co))

A very simple example to start with, right?  Here's what I thought
would be the working C implementation:

#include <lua.h>

int counter = 1;
static int _iter(lua_State *st)
{
    if(counter <= 3) {
        lua_pushinteger(st, counter++);
        return lua_yield(st, 1);
    }
    return 0;
}

static int iter(lua_State *st)
{
    lua_State *thread;
    thread = lua_newthread(st);
    lua_pushcfunction(thread, _iter);

    return 1;
}

int luaopen_test(lua_State *st)
{
    lua_pushcfunction(st, iter);
    lua_setglobal(st, "iterate");

    return 0;
}

This is in turn loaded from a Lua script:

require 'test'

co = iterate()
print(coroutine.resume(co))
print(coroutine.resume(co))
print(coroutine.resume(co))

The first resume works fine for my version, but then it segfaults.
I've poured over the documentation, existing code, the Lua source, the
mailing list archives and talked to people on IRC.  I'm either missing
something obvious or what I'm trying to do is impossible.  Please help
me out if you can!

-Rob Hoelz