memory question

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

memory question

Marc Balmer
Does collectgarbage('count') report only the memory the Lua core allocated or would it contain memory that a C function allocated using malloc()?


Reply | Threaded
Open this post in threaded view
|

Re: memory question

Matthew Wild
On 12 September 2016 at 13:58, Marc Balmer <[hidden email]> wrote:
> Does collectgarbage('count') report only the memory the Lua core allocated or would it contain memory that a C function allocated using malloc()?

Lua has no insight into what C code does with malloc(). Therefore it's
only memory allocated through Lua (or a C function allocating memory
through a Lua API).

Regards,
Matthew

Reply | Threaded
Open this post in threaded view
|

Re: memory question

Thomas Fletcher
In reply to this post by Marc Balmer

On Mon, Sep 12, 2016 at 8:58 AM, Marc Balmer <[hidden email]> wrote:
Does collectgarbage('count') report only the memory the Lua core allocated or would it contain memory that a C function allocated using malloc()?


Marc,

It only reports memory that has been allocated via the Lua core, so if you call malloc() to allocate content within your code and then bind it as light user data it will not be allocated.  However if you bind it using the Lua newuserdata() API then it will be accounted for because the allocation is 'coming through Lua'.

Thomas
Reply | Threaded
Open this post in threaded view
|

Re: memory question

Luiz Henrique de Figueiredo
In reply to this post by Marc Balmer
> Does collectgarbage('count') report only the memory the Lua core allocated or would it contain memory that a C function allocated using malloc()?

Lua uses a user-supplied function for memory allocation, which may not be
malloc. If you (like most people) create a Lua state using luaL_newstate,
instead of lua_newstate then Lua will use realloc, which shares the same
pool as malloc.

If you want to allocate memory through Lua, call lua_getallocf to get the
current allocator. The protocol for using this allocator is explained in
        https://www.lua.org/manual/5.3/manual.html#lua_Alloc

Using lua_newuserdata is equivalent but much more convenient than
calling the allocator manually.

Note that all memory allocated through Lua (either manually or with
lua_newuserdata) is subject to gargabe collection, and so you need to
anchor it somewhere inside the Lua state.