Discussion:
table.clear
Dirk Laurie
2018-09-26 12:20:55 UTC
Permalink
There is no 'clear' in the table library, so normally one would simply
reassign a new empty table. There are situations where this is
undesirable, e.g. more references to the table are lying around and
you want them to point to the cleared table; there may be values in
string-keyed fields etc.

The following monkey-patch can be used unless you have fiddled around
with metamethods.

table.clear = function(tbl)
local n=#tbl
table.move(tbl,n+1,2*n,1)
end

It relies on the proviso that there are not supposed to be any
non-nils at integer keys past the table's length.
Aapo Talvensaari
2018-09-26 14:43:53 UTC
Permalink
Post by Dirk Laurie
There is no 'clear' in the table library, so normally one would simply
reassign a new empty table. There are situations where this is
undesirable, e.g. more references to the table are lying around and
you want them to point to the cleared table; there may be values in
string-keyed fields etc.
I guess that's why LuaJITs table library [1] has table.new(narr, nrec) and
table.clear, and OpenResty's fork of LuaJIT [2] has table.clone. Just in
case you happen to use those implementations, and didn't know about
it already.

[1] https://github.com/LuaJIT/LuaJIT/blob/v2.1/src/lib_table.c#L288-L300
[2] https://github.com/openresty/luajit2
Egor Skriptunoff
2018-09-26 18:12:48 UTC
Permalink
LuaJITs table library has table.new(narr, nrec) and
table.clear.
Thanks!
I didn't know about undocumented require"table.clear"
Egor Skriptunoff
2018-09-26 18:18:50 UTC
Permalink
Post by Dirk Laurie
table.clear = function(tbl)
local n=#tbl
table.move(tbl,n+1,2*n,1)
end
Negative indices don't have "backwards" meaning in table.move(), so we can
write more compact code

table.clear = function(tbl)
table.move(tbl, -#tbl, -1, 1)
end
Dirk Laurie
2018-09-26 18:24:53 UTC
Permalink
Op Wo., 26 Sep. 2018 om 20:19 het Egor Skriptunoff
Post by Dirk Laurie
table.clear = function(tbl)
local n=#tbl
table.move(tbl,n+1,2*n,1)
end
Negative indices don't have "backwards" meaning in table.move(), so we can write more compact code
table.clear = function(tbl)
table.move(tbl, -#tbl, -1, 1)
end
I considered that possibility, but an array can have non-nils at
negative integer indices without violating the sequence property.
Loading...