src/lib/lua_func.h
author Tero Marttila <terom@fixme.fi>
Thu, 28 May 2009 01:17:36 +0300
branchnew-lib-errors
changeset 219 cefec18b8268
parent 201 src/lua_func.h@5c34c5d90a3f
permissions -rw-r--r--
some of the lib/transport stuff compiles
#ifndef LUA_FUNC_H
#define LUA_FUNC_H

/**
 * @file
 *
 * Convenience functions for working with lua C functions
 */
#include "lua_type.h"
#include <stdbool.h>

/**
 * Lua function argument types
 */
enum lua_arg_type {
    LUA_ARG_INVALID,
    
    /** A `const char *` pointing to lua-GC'd memory */
    LUA_ARG_STRING,

    /** A c99 `bool` */
    LUA_ARG_BOOL,

    /** A `long signed int` */
    LUA_ARG_INT,
};

/**
 * Function argument def
 */
struct lua_func_arg {
    /** Argument name */
    const char *name;

    /** Expected type */
    enum lua_arg_type type;

    /** Default value */
    union {
        const char *string;
        int boolean;
        long integer;
    } def;
};

/**
 * Function def
 */
struct lua_func {
    /** Object type, or NULL */
    const struct lua_type *type;

    /** Function name */
    const char *name;

    /** Help string */
    const char *help;

    /** Arguments */
    const struct lua_func_arg args[];
};

/**
 * Used as the "invalid" default value
 */
#define LUA_ARG_REQUIRED (-1)
#define LUA_ARG_STRING_REQUIRED ((const char *) (-1))

/**
 * Define a function argument
 */
#define LUA_FUNC_ARG_STRING(name, def) { (name), LUA_ARG_STRING, { .string = (def) } }
#define LUA_FUNC_ARG_BOOL(name, def) { (name), LUA_ARG_BOOL, { .boolean = (def) } }
#define LUA_FUNC_ARG_INT(name, def) { (name), LUA_ARG_INT, { .integer = (def) } }
#define LUA_FUNC_ARG_END { NULL, 0, { 0 } }

/**
 * Define a function
 */
#define LUA_FUNC(type, name, help, ...) { (type), (name), (help), { __VA_ARGS__, LUA_FUNC_ARG_END } }

/**
 * Parse and return a string argument
 */
const char *lua_arg_string (lua_State *L, int nargs, int index, const char *name, const char *def);

/**
 * Parse and return a boolean argument
 */
bool lua_arg_bool (lua_State *L, int nargs, int index, const char *name, int def);

/**
 * Parse and return an integer argument
 */
long lua_arg_int (lua_State *L, int nargs, int index, const char *name, long def);

/**
 * Return a userdata argument at the given fixed index
 */
void* lua_arg_obj (lua_State *L, int nargs, int index, const struct lua_type *type, bool optional);

/**
 * Parse function arguments as defined
 */
void lua_args_parse (lua_State *L, const struct lua_func *func, void **obj_ptr, ...);

#endif