lua-users home
lua-l archive

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


Am 25.11.2013 17:31 schröbte Dirk Laurie:
2013/11/25 Philipp Janda <siffiejoe@gmx.net>:

I'm interested in that as well. I took a look at the (Lua 5.2) source, and
it seems that a table is only ever resized if Lua can't find an empty slot
for a new element.

The comments say:

The actual size of the array is the largest `n' such that at
least half the slots between 0 and n are in use.

What do you make of that?


I guess that's the algorithm used to determine array and hash sizes when Lua resizes a table. I'm more concerned with *when* Lua decides to resize a table ... Lua doesn't resize as long as you only assign to existing keys (even if you assign nil) to keep the guarantee it made for the `next`[1] function.

  [1]: http://www.lua.org/manual/5.2/manual.html#pdf-next

Resizing happens in the `rehash` function which is only called from `luaH_newkey` when there are no free positions left in the hash part. The other relevant functions are `luaH_get`, `luaH_getint`, `luaH_set`, and `luaH_setint`. AFAICS, Lua never calls `luaH_newkey` (and `rehash`) as long as you assign within the array part or to existing keys in the hash part. If you assign to non-existing keys in the hash part, `luaH_newkey` is called, but it *only* causes a rehash/resize if no more hash slots are available. So you have to completely fill up the hash part to "release" table memory. I hope I'm missing something ...

Philipp