Re: A few questions about memory allocation
Javier Guerra Giraldez <[email protected]>
| Newsgroups | gmane.comp.lang.lua.general |
|---|---|
| Message-ID | <CAFkDaoRqHRtxT=M+uMP--QbJiBTnb4hy3vRFeGRN9FV8gHigRQ@mail.gmail.com> |
On Fri, 20 Feb 2026 at 15:26, 'Sewbacca' via lua-l <[email protected]> wrote: > I was wondering the other day how Lua handles memory allocations for a few > reasons. > > Sometimes it's nice to do calculations on the stack rather than on the > heap, if I know that the data is only used within that callframe. > This is especially true for vector calculations. In fact sometimes it > would be even better if I could pass vectors by value rather than by > reference, > because vectors are most of the time two to four numbers, so treating them > like numbers would be nice, but AFAIK Lua doesn't support that directly. > For some applications it would be beneficial to allocate on the stack > rather than the heap, even some larger userdatas/tables. > As in most interpreted, non-JITted languages, The "stack" in Lua actually resides in the heap (as seen from the underlying C implementation). While I think (could be wrong) primitive values (numbers, booleans, nil, lightuserdata) are passed by value and directly stored in the stack, anything slightly bigger would be handled by reference. even strings (although the deduplication makes them obey value semantics), or small "vectors" (implemented as tables?) are definitely allocated in the heap and passed by reference. > The next best thing would be to preallocate an arena and just hand > userdatas with pointers. > If I allocate a userdata object of a small size, say the size of a > pointer, does Lua allocate it on the heap or does it manage an arena of > some kind? > I suspect it allocates the data on the heap, so it's probably best to > allocate the C structure directly in the memory provided by Lua, rather > than calling malloc myself and just storing just a pointer right? > yes > Of course could manage my own arena and hand out light userdata objects, > but this means I cannot attach different metatables to different pointers. > or you could replace the allocator used by Lua with a thin wrapper to malloc that uses an arena for small objects. i guess some of the many "high performance" allocators do that in very sophisticated ways. -- Javier -- You received this message because you are subscribed to the Google Groups "lua-l" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion visit https://groups.google.com/d/msgid/lua-l/CAFkDaoRqHRtxT%3DM%2BuMP--QbJiBTnb4hy3vRFeGRN9FV8gHigRQ%40mail.gmail.com.