---
name: table
last_updated: 2026-12-04T23:21:36Z
type: library
summary: "A library of table functions."
---

# table

A library of table functions.

**Type:** library

## Description

This library provides generic functions for table/array manipulation,
providing all its functions inside the global [table](/docs/reference/engine/globals/table.md) variable. Most
functions in the [table](/docs/reference/engine/globals/table.md) library assume that the table represents an
array or a list. For these functions, the "length" of a table means the result
of the length operator.

## Functions

### table.clear

**Signature:** `table.clear(table: table): ()`

Sets the value for all keys within the given table to `nil`. This causes
the `#` operator to return `0` for the given table. The allocated capacity
of the table's array portion is maintained, which allows for efficient
re-use of the space.

This function does not delete/destroy the table provided to it. This
function is meant to be used specifically for tables that are to be
re-used.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `table` | `table` |  | The table whose keys will be cleared. |

**Returns:** `()`

**Table Clear**

Demonstrates the `table.clear` function, which empties a table so it can be
reused.

```lua
local grades = {95, 82, 71, 92, 100, 60}
print(grades[4], #grades) --> 92	6
table.clear(grades)
print(grades[4], #grades) --> nil	0

-- Reusing the same table avoids allocating a new one on every pass.
local scratch = {}
for round = 1, 3 do
	table.clear(scratch)
	for i = 1, round do
		scratch[i] = i * 10
	end
	print(round, #scratch) --> 1	1, then 2	2, then 3	3
end
```

### table.clone

**Signature:** `table.clone(t: table): table`

Returns an unfrozen shallow copy of the provided table.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `t` | `table` |  | The table to be cloned. |

**Returns:** `table` — The clone of the provided table.

**Table Clone**

Demonstrates the `table.clone` function, which makes a shallow, unfrozen copy
of a table.

```lua
local original = {
	key = "value",
	engine = "Roblox",
	tags = {"a", "b"},
}

local clone = table.clone(original)
clone.key = "changed"
print(original.key, clone.key) --> value	changed

-- The copy is shallow: nested tables are shared between both copies.
clone.tags[1] = "z"
print(original.tags[1]) --> z

-- Cloning a frozen table gives back a table that can be modified.
local frozen = table.freeze({1, 2, 3})
local thawed = table.clone(frozen)
print(table.isfrozen(thawed)) --> false
```

### table.concat

**Signature:** `table.concat(t: Array, sep: string, i?: int, j: int): string`

Given an array where all elements are strings or numbers, returns the
string `t[i] ... sep ... t[i+1] ... sep ... t[j]`. The default value for
sep is an empty string, the default for `i` is 1, and the default for `j`
is #t. If i is greater than `j`, returns the empty string.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `t` | `Array` |  | The table that will be converted into a string. |
| `sep` | `string` |  | The string that will be concatenated between each entry in the table. |
| `i` | `int` | `1` | The starting index of the table concatenation. |
| `j` | `int` |  | The ending index of the table concatenation. |

**Returns:** `string` — The concatenated string of table elements joined by the separator.

**Table Concat**

Demonstrates the `table.concat` function, which joins array elements into one
string.

```lua
local words = {"alpha", "beta", "gamma", "delta"}
print(table.concat(words)) --> alphabetagammadelta
print(table.concat(words, ", ")) --> alpha, beta, gamma, delta
print(table.concat(words, "-", 2, 3)) --> beta-gamma

-- Numbers are allowed too, but other value types raise an error.
print(table.concat({1, 2, 3}, "+")) --> 1+2+3

-- If i is greater than j the result is the empty string.
print(table.concat(words, ",", 3, 2) == "") --> true
```

### table.create

**Signature:** `table.create(count: number, value: Variant): table`

Creates a table with the array portion allocated to the given `number` of
elements, optionally filled with the given `value`.

If you are inserting into large array-like tables and are certain of a
reasonable upper limit to the number of elements, it's recommended to use
this function to initialize the table. This ensures the table's array
portion of its memory is sufficiently sized, as resizing it can be
expensive. For small quantities this is typically not noticeable.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `count` | `number` |  | The number of elements to allocate in the array portion of the new table. |
| `value` | `Variant` |  | The value to fill each element with. If omitted, elements are left as `nil`. |

**Returns:** `table` — A new table with the array portion pre-allocated to `count` elements,
filled with `value` if provided.

**Table Create**

Demonstrates the `table.create` function, which pre-sizes a table's array
portion.

```lua
local filled = table.create(3, "Roblox")
print(table.concat(filled)) --> RobloxRobloxRoblox

-- Without a value the elements are nil, but the capacity is reserved.
local empty = table.create(100)
print(#empty) --> 0

-- Pre-sizing avoids repeated array resizing when the final size is known.
local squares = table.create(50)
for i = 1, 50 do
	squares[i] = i * i
end
print(#squares, squares[50]) --> 50	2500
```

### table.find

**Signature:** `table.find(haystack: table, needle: Variant, init: number): Variant`

Within the given array-like table `haystack`, find the first occurrence of
value `needle`, starting from index `init` or the beginning if not
provided. If the value is not found, `nil` is returned.

A [linear search](https://en.wikipedia.org/wiki/Linear_search) algorithm
is performed.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `haystack` | `table` |  | The array-like table to search through. |
| `needle` | `Variant` |  | The value to search for within the table. |
| `init` | `number` |  | The index at which to begin searching. Defaults to `1`. |

**Returns:** `Variant` — The numeric index of the first occurrence of `needle`, or `nil` if not
found.

**Table Find**

Demonstrates the `table.find` function, which returns the index of the first
matching value.

```lua
local letters = {"a", "b", "c", "d", "e"}
print(table.find(letters, "d")) --> 4
print(table.find(letters, "z")) --> nil
print(table.find(letters, "b", 3)) --> nil

-- Only the first match is returned.
local repeated = {"x", "y", "x"}
print(table.find(repeated, "x")) --> 1
print(table.find(repeated, "x", 2)) --> 3
```

### table.freeze

**Signature:** `table.freeze(t: table): table`

This function makes the given table read-only, effectively "freezing" it
in its current state. Attempting to modify a frozen table throws an error.

This freezing effect is shallow, which means that you can write to a table
within a frozen table. To deep freeze a table, call this function
recursively on all of the descending tables.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `t` | `table` |  | The table to be frozen. |

**Returns:** `table` — The frozen table.

**Table Freeze**

Demonstrates the `table.freeze` function, which makes a table read-only.

```lua
local settings = table.freeze({volume = 5, nested = {muted = false}})

local ok, err = pcall(function()
	settings.volume = 10
end)
print(ok) --> false
print(string.find(err, "attempt to modify a readonly table", 1, true) ~= nil) --> true

-- Freezing is shallow, so nested tables can still be written to.
settings.nested.muted = true
print(settings.nested.muted) --> true

-- Deep freeze by freezing the descending tables as well.
local function deepFreeze(t)
	for _, value in t do
		if type(value) == "table" then
			deepFreeze(value)
		end
	end
	return table.freeze(t)
end

local config = deepFreeze({nested = {muted = false}})
print(table.isfrozen(config.nested)) --> true
```

### table.insert

**Signature:** `table.insert(t: Array, pos: number, value: Variant): ()`

Inserts `value` into array `t` at position `pos`, shifting up the elements
`t[pos], t[pos+1], ..., t[#t]` by one position. The position must be
between `1` and `#t` (inclusive) for the shift to occur; the value is then
written at `t[pos]`.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `t` | `Array` |  | The table that is being appended to. |
| `pos` | `number` |  | The position at which the value will be inserted. |
| `value` | `Variant` |  | The value that will be appended to the table. |

**Returns:** `()`

**Table Insert At Position**

Demonstrates the `table.insert` function inserting a value at a given
position.

```lua
local t = {"a", "b", "c"}
table.insert(t, 2, "new")
print(table.concat(t, ", ")) --> a, new, b, c

-- Inserting at position 1 shifts every element up.
table.insert(t, 1, "first")
print(table.concat(t, ", ")) --> first, a, new, b, c

-- Inserting at #t + 1 is the same as appending, so the position can be left out.
table.insert(t, "last")
print(table.concat(t, ", ")) --> first, a, new, b, c, last
```

### table.insert

**Signature:** `table.insert(t: Array, value: Variant): ()`

Appends `value` to the end of array `t` at position `#t + 1`. Unlike the
positional overload, no existing elements are shifted, making this the
most efficient way to grow an array by one element.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `t` | `Array` |  | The table that is being appended to. |
| `value` | `Variant` |  | The value that will be appended to the table. |

**Returns:** `()`

**Table Insert Append**

Demonstrates the `table.insert` function appending a value to the end of an
array.

```lua
local t = {"a", "b", "c"}
table.insert(t, "d")
print(table.concat(t, ", ")) --> a, b, c, d
print(#t) --> 4
```

### table.isfrozen

**Signature:** `table.isfrozen(t: table): bool`

This function returns `true` if the given table is frozen and `false` if
it isn't frozen. You can freeze tables using [table.freeze()](/docs/reference/engine/globals/table.md).

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `t` | `table` |  | The table to check. |

**Returns:** `bool` — Whether the table is frozen from [table.freeze()](/docs/reference/engine/globals/table.md).

**Table Isfrozen**

Demonstrates the `table.isfrozen` function, which reports whether a table is
frozen.

```lua
local data = {1, 2, 3}
print(table.isfrozen(data)) --> false

table.freeze(data)
print(table.isfrozen(data)) --> true

-- table.clone returns an unfrozen copy.
print(table.isfrozen(table.clone(data))) --> false
```

### table.maxn

**Signature:** `table.maxn(t: table): number`

Returns the maximum numeric key of the provided table, or zero if the
table has no numeric keys. Gaps in the table are ignored.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `t` | `table` |  | The table to scan for numeric keys. |

**Returns:** `number` — The largest positive numeric key in the table, or `0` if the table has
no numeric keys.

**Table Maxn**

Demonstrates the `table.maxn` function, which finds the largest numeric key in
a table.

```lua
print(table.maxn({"a", "b", "c"})) --> 3

-- Gaps are ignored, unlike the # operator which stops at a border.
local sparse = {"a", "b", [10] = "j"}
print(table.maxn(sparse)) --> 10

-- Non-numeric keys do not count.
print(table.maxn({name = "Rex"})) --> 0
```

### table.move

**Signature:** `table.move(src: table, a: number, b: number, t: number, dst?: table): table`

Copies elements in table `src` from `src[a]` up to `src[b]` into table
`dst` starting at index `t`. Equivalent to the assignment statement
`dst[t], ..., dst[t + (b - a)] = src[a], ..., src[b]`.

The default for `dst` is `src`. The destination range may overlap with the
source range. Returns `dst` for convenience.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `src` | `table` |  | Source table. |
| `a` | `number` |  | Start copying at `src[a]`. |
| `b` | `number` |  | Copy up to and including `src[b]`. |
| `t` | `number` |  | Copy into `dst[t], ...`. |
| `dst` | `table` | `src` | Destination table. |

**Returns:** `table` — `dst` for convenience.

**Table Move**

Demonstrates the `table.move` function, which copies a range of elements
between tables.

```lua
local sourceTable = {4, 5}
local destTable = {1, 2, 3}

table.move(
	sourceTable, -- Source table
	1, -- Index to start from in source table
	#sourceTable, -- Index up to (and including) from source table
	#destTable + 1, -- Index within destination table to move data into
	destTable -- Destination table
)
print(table.concat(destTable, ", ")) --> 1, 2, 3, 4, 5

-- Without a destination the elements are moved within the same table; ranges may overlap.
local queue = {"a", "b", "c", "d"}
table.move(queue, 2, 4, 1)
print(table.concat(queue, ", ")) --> b, c, d, d
```

### table.pack

**Signature:** `table.pack(values...: Variant): table`

Returns a new table with all arguments stored into keys 1, 2, etc. and
with a field "n" with the total number of arguments. Note that the
resulting table may not be a sequence.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `values...` | `Variant` |  | The values to store sequentially in the new table. |

**Returns:** `table` — A new table with arguments at keys `1` through `n`, plus an `n` field
storing the total argument count.

**Table Pack**

Demonstrates the `table.pack` function, which stores its arguments in a table
with a count field.

```lua
local t = table.pack(1, 2, 3)
print(table.concat(t, ", ")) --> 1, 2, 3
print(t.n) --> 3

-- The n field counts nil arguments, which the # operator may not.
local withNil = table.pack("a", nil, "c", nil)
print(withNil.n) --> 4
```

### table.remove

**Signature:** `table.remove(t: Array, pos: number): Variant`

Removes from array t the element at position pos, returning the value of
the removed element. When pos is an integer between `1` and `#t`, it
shifts down the elements `t[pos+1], t[pos+2], ..., t[#t]` and erases
element `t[#t]`. If the pos parameter is not provided, pos defaults to the
length of the table removing the last element.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `t` | `Array` |  | The table that is having an element removed. |
| `pos` | `number` |  | The index of the element being removed. |

**Returns:** `Variant` — The value of the element that was removed, or nothing if the position
is out of bounds.

**Table Remove**

Demonstrates the `table.remove` function, which removes an element and shifts
later ones down.

```lua
local t = {"a", "b", "c", "d"}

print(table.remove(t, 2)) --> b
print(table.concat(t, ", ")) --> a, c, d

-- Without a position the last element is removed.
print(table.remove(t)) --> d
print(table.concat(t, ", ")) --> a, c

-- Removing from an out-of-bounds position returns nothing.
print(table.remove(t, 10)) -->
print(#t) --> 2
```

### table.sort

**Signature:** `table.sort(t: Array, comp?: function): ()`

Sorts elements of array t in a given order, from `t[1]` to `t[#t]`. If
`comp` is given, then it must be a function that receives two elements and
returns true when the first element must come before the second in the
final order.

The error `invalid order function for sorting` is thrown if both
`comp(a, b)` and `comp(b, a)` return `true`.

If `comp` is not given, then the standard Luau operator `<` is used
instead.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `t` | `Array` |  | The array to sort in place. |
| `comp` | `function` | `nil` | An optional comparison function to be used when comparing elements in the table. This function receives two elements, and should return true if the first element should be sorted before the second in the final order. |

**Returns:** `()`

**Table Sort**

Demonstrates the `table.sort` function, which sorts an array in place.

```lua
local numbers = {5, 2, 8, 1}
table.sort(numbers)
print(table.concat(numbers, ", ")) --> 1, 2, 5, 8

-- A comparison function returns true when the first argument should come first.
table.sort(numbers, function(a, b)
	return a > b
end)
print(table.concat(numbers, ", ")) --> 8, 5, 2, 1

local players = {
	{name = "Ana", score = 30},
	{name = "Bo", score = 50},
	{name = "Cy", score = 40},
}
table.sort(players, function(a, b)
	return a.score > b.score
end)
print(players[1].name, players[2].name, players[3].name) --> Bo	Cy	Ana
```

### table.unpack

**Signature:** `table.unpack(list: table, i?: number, j?: number): Tuple`

Returns the elements from the given list. By default, `i` is 1 and `j` is
the length of `list`.

Note that this same functionality is also provided by the global
[LuaGlobals.unpack()](/docs/reference/engine/globals/LuaGlobals.md) function.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `list` | `table` |  | The list of elements to be unpacked. |
| `i` | `number` | `1` | The index of the first element to unpack. |
| `j` | `number` | `#list` | The index of the last element to unpack. |

**Returns:** `Tuple` — The elements `list[i], list[i+1], ..., list[j]` as individual return
values.

**Table Unpack**

Demonstrates the `table.unpack` function, which returns array elements as
separate values.

```lua
local position = {10, 20, 30}
local x, y, z = table.unpack(position)
print(x, y, z) --> 10	20	30

-- i and j select a range.
print(table.unpack(position, 2)) --> 20	30
print(table.unpack(position, 1, 2)) --> 10	20

-- The global unpack behaves the same way.
print(unpack == table.unpack) --> true
```

### table.foreach *(deprecated)*

**Signature:** `table.foreach(t: table, f: function): ()`

> **Deprecated:** This function is deprecated and should not be used in new work. Use a `for` loop instead.

Iterates over the provided table, passing the key and value of each
iteration over to the provided function. This function has been deprecated
and is not recommended for use in new code; use a `for` loop instead.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `t` | `table` |  | The table to be iterated over. |
| `f` | `function` |  | The function that will be used for the iteration. This function will receive 2 arguments for each iteration, where the 1st argument is the key, and the 2nd argument is the value. |

**Returns:** `()`

**Table Foreach**

Demonstrates the deprecated `table.foreach` function and the `for` loop that
replaces it.

```lua
local stock = {apples = 3}

table.foreach(stock, function(key, value)
	print(key, value) --> apples	3
end)

-- Preferred replacement:
for key, value in stock do
	print(key, value) --> apples	3
end
```

### table.foreachi *(deprecated)*

**Signature:** `table.foreachi(t: Array, f: function): ()`

> **Deprecated:** This function is deprecated and should not be used in new work. Use a `for` loop instead.

This is similar to [table.foreach()](/docs/reference/engine/globals/table.md) except that index-value pairs
are passed, not key-value pairs. This function has been deprecated and is
not recommended for use in new code; use a `for` loop instead.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `t` | `Array` |  | The table to be iterated over. |
| `f` | `function` |  | The function that will be used for the iteration. This function will receive 2 arguments for each iteration, where the 1st argument is the index, and the 2nd argument is the value. |

**Returns:** `()`

**Table Foreachi**

Demonstrates the deprecated `table.foreachi` function and the `for` loop that
replaces it.

```lua
local fruits = {"apple", "banana", "cherry"}

table.foreachi(fruits, function(index, value)
	print(index, value)
end)
--> 1	apple
--> 2	banana
--> 3	cherry

-- Preferred replacement:
for index, value in ipairs(fruits) do
	print(index, value)
end
```

### table.getn *(deprecated)*

**Signature:** `table.getn(t: Array): number`

> **Deprecated:** This function is deprecated and should not be used in new work. Use the `#` length operator instead.

Returns the number of elements in the table passed. This function has been
deprecated and is not recommended for use in new code; use `#t` instead.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `t` | `Array` |  | The table whose size is being measured. |

**Returns:** `number` — The length of the array portion of the table, equivalent to the `#`
operator.

**Table Getn**

Demonstrates the deprecated `table.getn` function and the `#` operator that
replaces it.

```lua
local queue = {"first", "second", "third"}
print(table.getn(queue)) --> 3

-- Preferred replacement:
print(#queue) --> 3
```