WoW:API tinsert

Revision as of 22:17, 30 December 2005 by WoWWiki>Muert

From TableLibraryTutorial of lua-users.org.

table.insert(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

Template:WoW API