API tremove

From TableLibraryTutorial of lua-users.org.

table.remove(table [, pos]) tremove(table[, pos])

Remove an element from a table. If a position is specified the element at that the position is removed. The remaining elements are reindexed sequentially and the size of the table is updated to reflect the change. The element removed is returned by this function. E.g.,

> t = { 1,"two",3,"four" }  -- create a table > = table.getn(t)           -- find the size 4 > table.foreach(t, print)   -- have a look at the elements 1      1 2       two 3      3 4       four > = table.remove(t,2)       -- remove element number 2 and display it two > table.foreach(t, print)   -- display the updated table contents 1      1 2       3 3       four > = table.getn(t)           -- find the size 3

If no position is given remove the last element in the table which is specified by the size of the table. E.g.,

> t = { 1,"two","three" } > = table.getn(t)          -- find the table size (which is removed) 3 > table.foreach(t, print)  -- display contents 1      1 2       two 3      three > = table.remove(t)        -- remove the element at position "n" three > table.foreach(t, print)  -- display updated contents 1      1 2       two > = table.getn(t)          -- display new size 2

If the size of the table does not reflect the number of elements nothing is removed, e.g.,

> t = {1,2,3} > table.setn(t,10)         -- set user size > table.foreach(t, print)  -- display table contents, note size "n" is stored internally 1      1 2       2 3       3 > = table.getn(t)           -- find the size 10 > = table.remove(t)        -- remove last element nil > = table.getn(t)          -- find the updated size 9 > table.foreach(t, print)  -- display elements 1      1 2       2 3       3