Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Lua Dictionary
  3. table.insert() / table.remove()

table.insert() / table.remove()

table.insert() and table.remove() are standard library functions for adding and removing elements in a Lua array table. They can also insert or remove at any position by specifying an index.

Syntax

-- -----------------------------------------------
-- table.insert — adding elements to a table
-- -----------------------------------------------
table.insert(t, v)           -- appends value v to the end of table t
table.insert(t, pos, v)      -- inserts value v at position pos in table t

-- -----------------------------------------------
-- table.remove — removing elements from a table
-- -----------------------------------------------
table.remove(t)              -- removes and returns the last element of table t
table.remove(t, pos)         -- removes and returns the element at position pos of table t

Function Reference

FunctionDescription
table.insert(t, v)Appends value v to the end of table t.
table.insert(t, pos, v)Inserts value v at position pos in table t. Subsequent elements are shifted back.
table.remove(t)Removes the last element from table t and returns it.
table.remove(t, pos)Removes the element at position pos from table t, returns it, and shifts subsequent elements forward.

Sample Code

sg_lab_members.lua
-- sg_lab_members.lua — sample for table.insert / table.remove
-- Operates on a member list for the Future Gadget Lab

-- -----------------------------------------------
-- Initial member list
-- -----------------------------------------------

local members = { "Okabe Rintaro", "Shiina Mayuri", "Hashida Itaru" }

print("=== Future Gadget Lab ===")
print("Initial members:")
for i, name in ipairs(members) do
    print(string.format("  %d. %s", i, name))
end
print("")

-- -----------------------------------------------
-- table.insert(t, v) — append to the end
-- -----------------------------------------------

-- Append Makise Kurisu to the end of the member list
table.insert(members, "Makise Kurisu")

print("After appending Makise Kurisu:")
for i, name in ipairs(members) do
    print(string.format("  %d. %s", i, name))
end
print("")

-- -----------------------------------------------
-- table.insert(t, pos, v) — insert at a specific position
-- -----------------------------------------------

-- Insert Amane Suzuha at position 2
table.insert(members, 2, "Amane Suzuha")

print("After inserting Amane Suzuha at position 2:")
for i, name in ipairs(members) do
    print(string.format("  %d. %s", i, name))
end
print("")

-- -----------------------------------------------
-- table.remove(t) — remove from the end
-- -----------------------------------------------

-- Remove the last member (the removed element is returned)
local removed = table.remove(members)
print("Removed from end: " .. removed)
print("After removal:")
for i, name in ipairs(members) do
    print(string.format("  %d. %s", i, name))
end
print("")

-- -----------------------------------------------
-- table.remove(t, pos) — remove at a specific position
-- -----------------------------------------------

-- Remove position 1 (Okabe Rintaro)
local expelled = table.remove(members, 1)
print("Removed position 1: " .. expelled)
print("After removal:")
for i, name in ipairs(members) do
    print(string.format("  %d. %s", i, name))
end
print("")

-- -----------------------------------------------
-- Using as a stack and queue
-- -----------------------------------------------

print("=== Stack (LIFO) ===")
local stack = {}
table.insert(stack, "Divergence Meter")     -- push
table.insert(stack, "IBN 5100")             -- push
table.insert(stack, "Future Gadget No. 8")  -- push
print("After push: " .. table.concat(stack, ", "))

local top = table.remove(stack)             -- pop (take from end)
print("pop: " .. top)
print("After pop: " .. table.concat(stack, ", "))
print("")

print("=== Queue (FIFO) ===")
local queue = {}
table.insert(queue, "D-Mail send request")  -- enqueue
table.insert(queue, "Lab fund operation")   -- enqueue
table.insert(queue, "Time leap experiment") -- enqueue
print("After enqueue: " .. table.concat(queue, ", "))

local front = table.remove(queue, 1)        -- dequeue (take from front)
print("dequeue: " .. front)
print("After dequeue: " .. table.concat(queue, ", "))
lua sg_lab_members.lua
=== Future Gadget Lab ===
Initial members:
  1. Okabe Rintaro
  2. Shiina Mayuri
  3. Hashida Itaru

After appending Makise Kurisu:
  1. Okabe Rintaro
  2. Shiina Mayuri
  3. Hashida Itaru
  4. Makise Kurisu

After inserting Amane Suzuha at position 2:
  1. Okabe Rintaro
  2. Amane Suzuha
  3. Shiina Mayuri
  4. Hashida Itaru
  5. Makise Kurisu

Removed from end: Makise Kurisu
After removal:
  1. Okabe Rintaro
  2. Amane Suzuha
  3. Shiina Mayuri
  4. Hashida Itaru

Removed position 1: Okabe Rintaro
After removal:
  1. Amane Suzuha
  2. Shiina Mayuri
  3. Hashida Itaru

=== Stack (LIFO) ===
After push: Divergence Meter, IBN 5100, Future Gadget No. 8
pop: Future Gadget No. 8
After pop: Divergence Meter, IBN 5100

=== Queue (FIFO) ===
After enqueue: D-Mail send request, Lab fund operation, Time leap experiment
dequeue: D-Mail send request
After dequeue: Lab fund operation, Time leap experiment

Common Mistakes

Common Mistake 1: Getting the argument order of table.insert wrong

The argument order for table.insert(t, pos, v) is "table, position, value". Passing position and value in the wrong order may insert at an unintended location or cause an error when a number is passed where a string is expected.

ng_insert_args.lua
local members = { "Okabe Rintaro", "Shiina Mayuri", "Hashida Itaru" }

-- Mistakenly passing arguments as (t, v, pos) in reverse order
table.insert(members, "Makise Kurisu", 2)   -- error or unintended behavior
stdin:1: bad argument #3 to 'insert' (number expected, got string)

The correct order is table.insert(table, position, value). To append to the end, omit the position: table.insert(t, v).

ok_insert_args.lua
local members = { "Okabe Rintaro", "Shiina Mayuri", "Hashida Itaru" }

-- Correct argument order: (table, position, value)
table.insert(members, 2, "Makise Kurisu")

for i, name in ipairs(members) do
    print(string.format("  %d. %s", i, name))
end
  1. Okabe Rintaro
  2. Makise Kurisu
  3. Shiina Mayuri
  4. Hashida Itaru

Common Mistake 2: Ignoring the return value of table.remove

table.remove(t, pos) returns the removed element as its return value. When implementing a stack or queue, forgetting to capture this return value means you lose access to the element you just removed.

ng_remove_return.lua
local tasks = { "D-Mail send request", "Lab fund operation", "Time leap experiment" }

-- Removing without capturing the return value loses the task name
table.remove(tasks, 1)
-- The name of the task to process is no longer accessible
print("Processed task: ???")
Processed task: ???

By capturing the return value in a variable, you can use the removed element in subsequent processing.

ok_remove_return.lua
local tasks = { "D-Mail send request", "Lab fund operation", "Time leap experiment" }

-- Capture the return value to use in processing
local current = table.remove(tasks, 1)
print("Processing task: " .. current)
print("Remaining tasks: " .. #tasks)
Processing task: D-Mail send request
Remaining tasks: 2

Overview

table.insert(t, v) appends an element to the end of an array table t, while table.insert(t, pos, v) inserts at the specified position pos and shifts subsequent elements back. table.remove(t) removes and returns the last element, while table.remove(t, pos) removes and returns the element at the specified position and shifts subsequent elements forward. Applying table.insert and table.remove only at the end gives O(1) stack operations, but operating at the front for a queue incurs O(n) shifting proportional to the number of elements, so care is needed with large data sets. The current element count of a table can be obtained with #t. For how to create tables, see also Table Basics.

If you find any errors or copyright issues, please .