Cpp Stream Chunk Reader

lua-users home
wiki

This is a lua_load chunk reader for any std::istream. Obviously, it requires C++. I adapted the snippet from some other code I had laying around, so apologies if it doesn't work right away. Please fix it if you discover problems.

// this is not threadsafe
const char* istream_ChunkReader( lua_State *L, void *data, size_t *size )
{
    const size_t kBufferSize = 1024;
    static char s_buffer[kBufferSize];

    std::istream* pis = reinterpret_cast<std::istream*>(data);
    if ( !pis )
        return NULL;
    pis->read( &s_buffer[0], kBufferSize );
    *size = pis->gcount();
    return s_buffer;
}

// type-safe wrapper
int lua_load_stream( lua_State *L, std::istream& is, const std::string& chunkname = "" )
{
    return lua_load( L, &istream_ChunkReader, &is,
                     chunkname.empty() ? NULL : chunkname.c_str() );
}

// it would be invoked like so:
lua_State* L = some_lua_state;
std::istream& is = some_stream_from_somewhere;
int res = lua_load_stream( L, is, "my chunk name" );


RecentChanges · preferences
edit · history
Last edited February 8, 2007 7:17 pm GMT (diff)