Explorar o código

New function 'table.create'

Creates a table preallocating memory. (It just exports to Lua the API
function 'lua_createtable'.)
Roberto Ierusalimschy hai 1 ano
pai
achega
3e9dbe143d
Modificáronse 3 ficheiros con 45 adicións e 2 borrados
  1. 9 0
      ltablib.c
  2. 15 2
      manual/manual.of
  3. 21 0
      testes/sort.lua

+ 9 - 0
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},

+ 15 - 2
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},

+ 21 - 0
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