lua-users home
lua-l archive

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


Is there any reason why Lua doesn't allow C functions to be used with coroutines directly? As far as I can tell the code only needs two small changes to get these to work, and one of them is the check in luaB_cocreate to make sure you're passing in a Lua function. It would mean you can pass C functions into coroutine.create, provided you handle the internal suspend/resume logic yourself

#define YIELD() {lua_yield(L, 0); return -1;}

static int foo(lua_State *L)
{
   static int foo_state = 0;
   switch (foo_state++)
   {
       case 0:
           lua_getglobal(L, "print");
           lua_pushstring(L, "Hello World!");
           lua_call(L, 1, 0);
           lua_yield(L, 0);
           YIELD();

       case 1:
           lua_getglobal(L, "print");
           lua_pushstring(L, "Goodbye World!");
           lua_call(L, 1, 0);   /* fallthrough */
   }

   return 1; // die
}

And then in the Lua code you do this:

local co = coroutine.create(foo)
coroutine.resume(co)        --> Hello World!
coroutine.resume(co)        --> Goodbye World!
print(coroutine.status(co))    --> dead

Does anyone else think this would be a worthwhile addition? I'm currently in the process of experimenting with some optimizations where large portions of Lua script are automatically converted to C code that is then statically linked to the program. It's basically impossible to do this properly without adding some sort of support for C coroutines.

Mark Feldman


This message and its attachments may contain legally privileged or confidential information. This message is intended for the use of the individual or entity to which it is addressed. If you are not the addressee indicated in this message, or the employee or agent responsible for delivering the message to the intended recipient, you may not copy or deliver this message or its attachments to anyone. Rather, you should permanently delete this message and its attachments and kindly notify the sender by reply e-mail. Any content of this message and its attachments, which does not relate to the official business of the sending company must be taken not to have been sent or endorsed by the sending company or any of its related entities. No warranty is made that the e-mail or attachment(s) are free from computer virus or other defect.