Trusted answers to developer questions
Trusted Answers to Developer Questions

RELATED TAGS

php
lua

What is the table.remove() function in Lua?

NDUKWE CHIDERA K.

Overview

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.

The table.remove () function

The 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.

Syntax

table.remove(tableName,pos)

Parameter

  • 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.

Returns

The function returns the removed value.

Code

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 table
myEvens = {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))
Using the table.remove() function in Lua

Explanation

  • Lines 3, 8, and 13: We declare the table values.
  • Line 5: We remove the value at the table’s end because the pos parameter is not provided.
  • Lines 10 and 15: We remove the value at the indicated position in the table using the pos parameter. Then, we print the value to the console.

RELATED TAGS

php
lua
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.

soc2