src/lua_thread.h
author Tero Marttila <terom@fixme.fi>
Thu, 21 May 2009 16:23:50 +0300
branchlua-threads
changeset 207 3fa22abb5421
parent 204 7dfc3d7bd92b
child 210 05abca972db0
permissions -rw-r--r--
fix lua_nexus_sleep to use EV_TIMEOUT + misc
#ifndef LUA_THREAD_H
#define LUA_THREAD_H

/**
 * @file
 *
 * Running code as lua coroutines for a nexus_lua
 */
#include "nexus_lua.h"
#include <lua5.1/lua.h>

/*
 * Forward-declare
 */
struct lua_thread;

/**
 * Callback for async execution completion. The thread will be cleaned up for re-use before this is called.
 *
 * Called with err == NULL for success, error code otherwise.
 *
 * XXX: also return execution results (as a lua_State arg)?
 */
typedef void (*lua_thread_cb) (const error_t *err, void *arg);

/**
 * A thread of execution
 */
struct lua_thread {
    /** The lua_nexus environment we're running under */
    struct nexus_lua *lua;

    /** Callback */
    lua_thread_cb cb_func;

    /** Callback context argument */
    void *cb_arg;

    /** Real lua thread state */
    lua_State *L;
};

/**
 * Initialize the given lua_thread state for execution.
 *
 * You only need to call this once for each lua_thread that you use.
 */
void lua_thread_init (struct lua_thread *thread, struct nexus_lua *lua, lua_thread_cb cb_func, void *cb_arg);

/**
 * Execute the given chunk in a thread context.
 *
 * This should be called from unprotected mode, and the thread must currently not be active.
 *
 * This will load the chunk, create a new lua thread state off the lua_nexus, and then do the initial 'lua_resume' call
 * on the loaded chunk, to execute up to the first yield or final return.
 *
 * If this process raises an error, it will be returned directly. If the called chunk simply returns without yielding,
 * this returns 0, and the callback is *NOT* called. Otherwise, this returns >0 and the thread's callback function will
 * eventually be called once the thread either errors out or finishes execution.
 */
int lua_thread_start (struct lua_thread *thread, const char *chunk, error_t *err);

/**
 * Protected-mode function to resume execution of the given lua_State, which must be a lua_State created with
 * lua_thread_start.
 */
void lua_thread_resume_state (lua_State *L);

#endif