Cpp Stream Chunk Reader

lua-users home
wiki

Showing revision 2
This is a lua_load chunk reader for a 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;
}

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


RecentChanges · preferences
edit · history · current revision
Edited February 8, 2007 4:03 am GMT (diff)