API tinsert

From Warcraft Wiki
Jump to navigation Jump to search

From TableLibraryTutorial of lua-users.org.

table.insert(table, [pos,] value)
tinsert(table[, pos], value)

Insert a given value into a table. If a position is given insert the value before the element currently at that position:

> t = { 1,3,"four" }
> table.insert(t, 2, "two")  -- insert "two" at position before element 2
> = table.concat(t, ", ")
1, two, 3, four

If no position is specified we append the value to the end of the table:

> table.insert(t, 5)         -- no position given so append to end
> = table.concat(t, ", ")
1, two, 3, four, 5

When a table has an element inserted both the size of the table and the element indices are updated:

> t = { 1,"two",3 }               -- create a table
> = table.getn(t)                 -- find current size
3
> table.foreach(t, print)         -- display the table contents
1       1
2       two
3       3
> table.insert(t, 1, "inserted")  -- insert an element at the start
> = table.concat(t, ", ")         -- see what we have
inserted, 1, two, 3
> = table.getn(t)                 -- find the size
4
> table.foreach(t, print)         -- the indexes have been updated
1       inserted
2       1
3       two
4       3

When no position is specified the element is inserted at the end of the table according to the calculated size. The size of a table may be user specified and not reflect the number of elements, e.g.,

> t = { 1,"two",3; n=10 }  -- create a table with user size
> table.insert(t, "end")   -- insert with no position inserts at "end"
> table.foreach(t, print)  -- display the table contents
1       1
2       two
3       3
11      end
n       11


Speed

If you are appending to an integer-indexed table, it is always faster to track the size yourself, as this example demonstrates (clocked on a 3Ghz P4)

local t = {}
local tinsert=table.insert

local b = os.clock()

local n=1
t.n=1
for i=1,5e6 do
	table.insert(t, "")  -- 2.25s - extra cost of looking up table. subkeys
	tinsert(t, "")       -- 2.02s - local function call is slightly faster
	t[#t+1] = ""         -- 1.72s - a lot of the cost seems to be #t
	local tn=t.n; t[tn]=""; t.n=tn+1   -- 1.19s - storing "n" in the table
	t[n]="";n=n+1        -- 0.88s - storing "n" in a local
	t[i]=""              -- 0.78s - cheat, we don't have "i" usually
	-- empty   -- 0.08s overhead for the loop
end

local e = os.clock()
print(e-b)


See Also