What is the table.insert() method in Lua?
Overview
The table.insert() method adds values to a table structure. It inserts the value at a given index, causing other values to adjust accordingly. The value and the target index are passed as parameters to the method. It appends a value at the end of the table when no specific location is provided.
Syntax
table.insert(tableVal, index, newValue)
Parameters
-
tableVal: This is the table structure in which the valuenewValueis to be inserted. -
index: This is a numeric value that specifies the position intableValin which the valuenewValueis to be inserted. This is an optional parameter. -
newValue: This is the value that we want to insert intableVal.
Return value
The table.insert() method returns an array with the new value inserted in it.
Code
The code snippet below demonstrates a sample value insertion.
--declare variablestableVal = {"You" ,"can't", "believe" , "it"}newValue1 = "absolutely"newValue2 = "really"newValue3 = "surely"--call the table.remove method.table.insert(tableVal, 2, newValue1)table.insert(tableVal, 3, newValue2)table.insert(tableVal, newValue3)--print the value to displayfor key,value in ipairs(tableVal) doprint(key,value)end
Explanation
-
Line 2: We declare a table structure in which we’ll insert the new values.
-
Lines 3 to 5: We declare some variables to insert in
tableVal. -
Lines 8–10: We insert values
newValue1andnewValue2in positions 2 and 3, respectively. We also insertnewValue3for which we don’t specify a position. -
Lines 13 to 15: We use the
forloop to go through the table and print its values along with their indexes.