commit 3e9dbe143d3338f5f13a5e421ea593adff482da0
parent 4a8e48086433ad12f2991c07f3064278714fd0f1
Author: Roberto Ierusalimschy <roberto@inf.puc-rio.br>
Date: Thu, 18 Jan 2024 15:15:59 -0300
New function 'table.create'
Creates a table preallocating memory. (It just exports to Lua the API
function 'lua_createtable'.)
Diffstat:
3 files changed, 45 insertions(+), 2 deletions(-)
diff --git a/ltablib.c b/ltablib.c
@@ -58,6 +58,14 @@ static void checktab (lua_State *L, int arg, int what) {
}
+static int tcreate (lua_State *L) {
+ int sizeseq = (int)luaL_checkinteger(L, 1);
+ int sizerest = (int)luaL_optinteger(L, 2, 0);
+ lua_createtable(L, sizeseq, sizerest);
+ return 1;
+}
+
+
static int tinsert (lua_State *L) {
lua_Integer pos; /* where to insert new element */
lua_Integer e = aux_getn(L, 1, TAB_RW);
@@ -390,6 +398,7 @@ static int sort (lua_State *L) {
static const luaL_Reg tab_funcs[] = {
{"concat", tconcat},
+ {"create", tcreate},
{"insert", tinsert},
{"pack", tpack},
{"unpack", tunpack},
diff --git a/manual/manual.of b/manual/manual.of
@@ -3234,11 +3234,11 @@ Values at other positions are not affected.
}
-@APIEntry{void lua_createtable (lua_State *L, int narr, int nrec);|
+@APIEntry{void lua_createtable (lua_State *L, int nseq, int nrec);|
@apii{0,1,m}
Creates a new empty table and pushes it onto the stack.
-Parameter @id{narr} is a hint for how many elements the table
+Parameter @id{nseq} is a hint for how many elements the table
will have as a sequence;
parameter @id{nrec} is a hint for how many other elements
the table will have.
@@ -7969,6 +7969,19 @@ If @id{i} is greater than @id{j}, returns the empty string.
}
+@LibEntry{table.create (nseq [, nrec])|
+
+Creates a new empty table, preallocating memory.
+This preallocation may help performance and save memory
+when you know in advance how many elements the table will have.
+
+Parameter @id{nseq} is a hint for how many elements the table
+will have as a sequence.
+Optional parameter @id{nrec} is a hint for how many other elements
+the table will have; its default is zero.
+
+}
+
@LibEntry{table.insert (list, [pos,] value)|
Inserts element @id{value} at position @id{pos} in @id{list},
diff --git a/testes/sort.lua b/testes/sort.lua
@@ -3,6 +3,27 @@
print "testing (parts of) table library"
+do print "testing 'table.create'"
+ collectgarbage()
+ local m = collectgarbage("count") * 1024
+ local t = table.create(10000)
+ local memdiff = collectgarbage("count") * 1024 - m
+ assert(memdiff > 10000 * 4)
+ for i = 1, 20 do
+ assert(#t == i - 1)
+ t[i] = 0
+ end
+ assert(not T or T.querytab(t) == 10000)
+ t = nil
+ collectgarbage()
+ m = collectgarbage("count") * 1024
+ t = table.create(0, 1024)
+ memdiff = collectgarbage("count") * 1024 - m
+ assert(memdiff > 1024 * 12)
+ assert(not T or select(2, T.querytab(t)) == 1024)
+end
+
+
print "testing unpack"
local unpack = table.unpack