[Home] [Downloads] [Search] [Help/forum]



Inserts a new item into a numerically-keyed table


table.insert (t, pos, value)


Inserts the value at (optional) position 'pos', renumbering existing elements if necessary to make room. Thus the new element becomes the one with index 'pos'.

If called with 2 arguments, the value is inserted at n+1, that is, the end of the table.

t = { "the", "quick", "brown", "fox" }
table.insert (t, 2, "very") -- new element 2
table.insert (t, "jumped")  -- add to end of table
table.foreachi (t, print)


1 the
2 very
3 quick
4 brown
5 fox
6 jumped

The Lua authors recommend using the idiom "#t + 1" to insert to the end of a table nowadays. For example:

t = {}
t [#t + 1] = "hello, "
t [#t + 1] = "world"

Note that for other keys (eg. strings) you simply assign to the table item to insert it. For example:

t = {}
t.foo = "bar"    -- insert key "foo"
t ["Nick Gammon"] = 42  -- insert key "Nick Gammon"

See Also ...

Lua functions

table.concat - Concatenates table items together into a string
table.foreach - Applies a function to each item in a table
table.foreachi - Applies a function to each item in a numerically-keyed table
table.getn - Returns the size of a numerically-keyed table
table.maxn - Returns the highest numeric key in the table
table.remove - Removes an item from a numerically-keyed table
table.setn - Sets the size of a table (obsolete)
table.sort - Sorts a table


Lua base functions
Lua bc (big number) functions
Lua bit manipulation functions
Lua coroutine functions
Lua debug functions
Lua io functions
Lua LPEG library
Lua math functions
Lua os functions
Lua package functions
Lua PCRE regular expression functions
Lua script extensions
Lua string functions
Lua syntax
Lua table functions
Lua utilities
Scripting callbacks - plugins

(Help topic: lua=table.insert)

Documentation contents page

Search ...

Enter a search string to find matching documentation.

Search for:   

Quick links: MUSHclient. MUSHclient help. Forum shortcuts. Posting templates. Lua modules. Lua documentation.

Information and images on this site are licensed under the Creative Commons Attribution 3.0 Australia License unless stated otherwise.


Written by Nick Gammon - 5K   profile for Nick Gammon on Stack Exchange, a network of free, community-driven Q&A sites   Marriage equality

Comments to: Gammon Software support
[RH click to get RSS URL] Forum RSS feed ( https://gammon.com.au/rss/forum.xml )

[Best viewed with any browser - 2K]    [Hosted at FutureQuest]