In Lua, there are a handful of methods that we can use to manipulate an array, which is same as a table in this language. The table.remove()
function will remove an element from a table, thereby reducing the length of the table by 1. It removes one element at a time.
table.remove ()
functionThe table.remove ()
function removes a value from an array using the index position of the value to be removed.
This function removes the element at the pos
position from the table. This causes other elements to shift down to close the space, if necessary.
This function returns the value that we remove from the table. The pos
parameter has a default value of n
, which is the length of the table. This causes the last element of the table to be removed if the pos
parameter is not provided.
table.remove(tableName,pos)
tableName
: This is name of the table from which you wish to remove a value.
pos
: This is the position in the tableName
table where the value to be removed is located.
The function returns the removed value.
Let’s see an example. Some elements will be removed from a few tables in the code snippet below.
-- Declare the table value.myName = {"smith","mark","queen"}-- Print the values after using the table.remove method.print (table.remove(myName))-- Declare a tablemyEvens = {2,4,6,8,10}-- Print the values after using the table.remove method.print (table.remove(myEvens, 3))-- Declare another table.myMix = {2,"mark",3,"skin",9}-- Print the values after using the table.remove method.print (table.remove(myMix,4))
pos
parameter is not provided.pos
parameter. Then, we print the value to the console.