lua-users home
lua-l archive

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


> I need a dynamically allocated buffer for a unicode string in win32
> is there a lua API function to alloc a memory buffer inside a
> cfunction and let the garbage collector free it later
> (function that does not push something to the statck)

Have a look at the lua_newuserdata call:

    http://www.lua.org/manual/5.0/manual.html#3.8

It allocates a buffer of a specified size, pushes it as a userdata object on
the stack and returns a pointer to the buffer area.  If you pop the userdata
from the stack and it is not stored some place else (globals, some table,
...) it will be garbage collected later on.  Example:

    void *buf = lua_newuserdata(L, 1024);
    /* do something with buf here... */
    /* pop userdata (will be collected at some point) */
    lua_pop(L, 1);

The userdata must be pushed on the stack or it could get garbage collected
too early!

Bye,
Wim