lua-users home
lua-l archive

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


Thanks to some excellent feedback from lhf, we're already up to version 1.1
of the constant table code.

This version is compatible with plain C, doesn't have the temporary
variable, and uses a lua_beginblock/lua_endblock pair.

Also, lhf points out that the following code DOES work:

#define PI 3.14
CONST_TABLE_BEGIN("MY_TABLE")
    CONST_NUM( "PI", PI )
CONST_TABLE_END

So there's reason to rejoice.  :-)

Thanks, lhf!

ashley

--- cut here ---

#define CONST_TABLE_BEGIN( TABLE_NAME ) \
    lua_beginblock(); {\
    lua_Object err_func;\
    int tag;\
    lua_Object table = lua_createtable();\
    lua_pushobject( table );\
    lua_setglobal( TABLE_NAME );\
    lua_dostring( "return function () error(\
    \"Cannot modify constant table: " TABLE_NAME "\" ) end" );\
    err_func = lua_lua2C( 1 );

#define CONST_NUM( NAME, VALUE) \
    lua_pushobject( table );\
    lua_pushstring( ( char * ) NAME );\
    lua_pushnumber( VALUE );\
    lua_settable();

#define CONST_NUM_VAR( NAME ) \
    lua_pushobject( table );\
    lua_pushstring( ( char * ) #NAME );\
    lua_pushnumber( NAME );\
    lua_settable();

#define CONST_STR( NAME, VALUE ) \
    lua_pushobject( table );\
    lua_pushstring( ( char * ) NAME );\
    lua_pushstring( VALUE );\
    lua_settable();

#define CONST_STR_VAR( NAME ) \
    lua_pushobject( table );\
    lua_pushstring( ( char * ) #NAME );\
    lua_pushstring( ( char * ) NAME );\
    lua_settable();

#define CONST_TABLE_END \
    tag = lua_newtag();\
    lua_pushobject( table );\
    lua_settag( tag );\
    lua_pushobject( table );\
    lua_pushobject( err_func );\
    lua_settagmethod( tag, "settable" );\
    lua_pushobject( table );\
    lua_pushobject( err_func );\
    lua_settagmethod( tag, "setglobal" );\
    } lua_endblock();

--- cut here ---