lua-users home
lua-l archive

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


Dirk Feytons wrote:
> I was looking at the luaL_Buffer mechanism. I know it is intended for
> collecting lots of small strings but luaL_prepbuffer() seems useful
> for my scenario. Could I use this to allocate space and pass the
> pointer to the read_data() function, then do a luaL_addsize() and
> luaL_pushresult()? Is it guaranteed that if some Lua function raises
> an error the luaL_Buffer memory is freed?

The luaL_Buffer mechanism uses a fixed size buffer on the C stack
(LUAL_BUFFERSIZE = BUFSIZ = usually 4K or 8K) and pushes partial
Lua strings on the Lua stack if the buffer overflows. No memory
leak can result, since the C stack is just reset on error and Lua
strings are garbage collected.

But this also means you need to split the read into pieces. Have
a look at the read_chars() function in liolib.c. Another subtle
point: you need to keep the Lua stack at the same level before
calling any of the buffer functions (put any slots you need at
fixed positions below the buffer slots).