lua-users home
lua-l archive

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



On Feb 21, 2009, at 10:29 AM, Bertrand Mansion wrote:



Is there something wrong with this code ?
Also, is there something wrong in using malloc/free in Lua modules ?


At first glance I see nothing wrong with the code, but it's been a while since I've dealt with this.

The reason for using lua_getallocf() instead of malloc/free is so that the Lua user's allocation function is used. The user can define an allocator that is more efficient for their operating system (esp. embedded systems which might have small amounts of memory), and this allocator might not use malloc/free or might malloc/free larger chunks at once to prevent memory fragmentation. By using lua_getallocf you can take advantage of those things.

In addition, running out of memory using the user's allocator function causes Lua to throw an out-of-memory error, which is catchable by pcall, etc. malloc/free would not normally do this without further programming.

(Lua's allocator function can be overwritten by the C API or by other modules with lua_setallocf.)


--
Bertrand Mansion
Mamasam