Re: Function to force table to shrink?
Gé Weijers <[email protected]>
| Newsgroups | gmane.comp.lang.lua.general |
|---|---|
| Message-ID | <CAGj8prgC08NxGfB0NykK+y0EHFGO8OJAqM7TJQ2nssJScUD+Lw@mail.gmail.com> |
On Fri, Jan 30, 2026 at 12:09 PM 'Martin Eden' via lua-l < [email protected]> wrote: > > > Stock "table" module functions (concat, pack, unpack, sort, insert, > remove, move) do produce results observable in code. You can write > test for them. > > Empty table slots (t['a'] = nil) are not observable. pairs() will never > return you key with nil value. > > A 'rehash' would change the order in which 'next' and therefor 'pairs' would return key-value pairs, and when 'rehash' is called during an iteration you'd likely see duplicate values. You cannot add new key values to a table during an iteration for the same reason. One primitive that could be useful instead of 'table.rehash' would be a 'table.swap', which would swap the contents of two distinct tables, i.e. swap the array and hash table sections of the two tables and their metatables without allocating or deallocating anything. The garbage collector would have to be aware of this, I assume, just like it has to be aware of growing a table. A rehash could look like the following code, and you could do more with this, like make a table read-only by introducing a proxy table in O(1) time. local function rehash(t) local new_t = {} for k, v in pairs(t) do new_t[k] = v end table.swap(t, new_t) end local function read_only(t) local proxy = {} local mt = { __index = proxy, __newindex = refuse, -- left to the reader __pairs = function(_) return pairs(proxy) end, } setmetatable(proxy, mt) table.swap(t, proxy) end Just an idea. -- Gé -- 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/CAGj8prgC08NxGfB0NykK%2By0EHFGO8OJAqM7TJQ2nssJScUD%2BLw%40mail.gmail.com.