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 value newValue is to be inserted.

  • index: This is a numeric value that specifies the position in tableVal in which the value newValue is to be inserted. This is an optional parameter.

  • newValue: This is the value that we want to insert in tableVal.

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 variables
tableVal = {"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 display
for key,value in ipairs(tableVal) do
print(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 newValue1 and newValue2 in positions 2 and 3, respectively. We also insert newValue3 for which we don’t specify a position.

  • Lines 13 to 15: We use the for loop to go through the table and print its values along with their indexes.

Free Resources