src/spbot/lua_thread.h
author Tero Marttila <terom@fixme.fi>
Thu, 28 May 2009 00:35:02 +0300
branchnew-lib-errors
changeset 218 5229a5d098b2
parent 210 src/lua_thread.h@05abca972db0
permissions -rw-r--r--
some of spbot and lib compiles
#ifndef SPBOT_LUA_THREAD_H
#define SPBOT_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 yield execution of the given lua_State, which must be a luaState created with
 * lua_thread_start.
 *
 * This should be called the same way as lua_yield, except no results are supported yet.
 */
int lua_thread_yield_state (lua_State *L);

/**
 * 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);

/**
 * Abort execution of the given thread, if it's running.
 *
 * Currently, there is no mechanism to actually abort a running thread, so this will instead release the lua_thread for
 * new use, and then cause the lua_thread_resume to do nothing. 
 */
void lua_thread_abort (struct lua_thread *thread);

#endif