lua-users home
lua-l archive

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

on 10/10/05 6:36 PM, Chris Marrin at wrote:

> It would be nice if Lua had an efficient way to expose internalized
> strings to C. Anyone know of any good tricks?

I agree that this can be a source of hidden expense.

My solution, but I also have to admit that I haven't benchmarked it is to do
something like the following:

    void pushconststring( lua_State *L, const char *str ) {

        lua_pushlightuserdata( L, str );
        lua_gettable( L, LUA_REGISTRYINDEX );

        if( lua_isnil( L, -1 ) ) {
            // Not in the registry, so put it there
            lua_pop( L, 1 );
            lua_pushstring( L, str );
            lua_pushlightuserdata( L, str );
            lua_pushvalue( L, -2 );
            lua_settable( L, LUA_REGISTRYINDEX );


This also works as a way to avoid pushing C functions repeatedly if one
abuses the fact that C function pointers aren't really supposed to be cast
to void*'s.

What might make this idiom more efficient would be something like:

    int lua_rawgetud( lua_State *L, int index, const void *key );
        /* Returns 1 if it found an entry and leaves the entry
        on the stack. Returns 0 and does not change the stack if
        it doesn't find an entry. */

But as I said above, I've been lax and haven't profiled extensively to
confirm that this is a problem worth solving. With respect to functions, I
was more concerned with avoiding the overhead of creating new objects
repeatedly. That issues doesn't apply to strings.