Kahibaro
Discord Login Register

2.1.4 Tables

Why Tables Matter in Lua

Tables are the most important data structure in Lua. Lua does not have built in arrays, lists, dictionaries, or objects. Instead it has a single flexible type, the table, and you can use it to represent all of those structures. Almost every nontrivial Roblox script uses tables somewhere, so understanding them early will help you with later topics like events, inventories, and player data.

Creating Your First Table

You create a table with curly braces. An empty table looks like this:

local myTable = {}

You can also create a table with some values right away:

local colors = {"Red", "Green", "Blue"}

Here colors holds three values. At this point you can think of it as a simple list.

You can create a table with named fields as well:

local playerInfo = {
    Name = "Alex",
    Level = 1
}

Here playerInfo has two named pieces of data, Name and Level.

Accessing Values in Tables

To read values from a table that acts like a list, you use square brackets with a number:

local colors = {"Red", "Green", "Blue"}
local firstColor = colors[1]
local secondColor = colors[2]

Lua uses 1 based indexing. The first element is at index 1, not 0.

For tables that use names as keys, you can access values in two ways.

With dot syntax:

local playerInfo = {
    Name = "Alex",
    Level = 1
}
print(playerInfo.Name)
print(playerInfo.Level)

Or with square brackets and a string:

print(playerInfo["Name"])
print(playerInfo["Level"])

Both forms read the same data. Dot syntax is shorter and is usually used when the key is a valid name without spaces.

Important rule: Lua tables are 1 based by default. If you create a list like local t = {"a", "b", "c"}, then t[1] is "a", t[2] is "b", and t[3] is "c". Index 0 is not used unless you manually assign it.

Changing Values in Tables

You can update values in a table by assigning to them.

For list style tables:

local colors = {"Red", "Green", "Blue"}
colors[2] = "Yellow"

Now the table contents are "Red", "Yellow", "Blue".

For table fields with names:

local playerInfo = {
    Name = "Alex",
    Level = 1
}
playerInfo.Level = 2
playerInfo["Name"] = "Jordan"

You can also add new entries simply by assigning to a new key:

playerInfo.Experience = 50
playerInfo["Coins"] = 10

If a key did not exist before, Lua creates it and stores the value.

Adding and Removing List Elements

Lua provides some standard functions in the table library to work with tables used as lists.

To insert a value at the end of a list:

local colors = {"Red", "Green"}
table.insert(colors, "Blue")

Now colors[3] is "Blue".

You can also insert at a specific position:

table.insert(colors, 2, "Yellow")

This moves existing elements to the right and puts "Yellow" at index 2.

To remove and return the last element:

local last = table.remove(colors)

To remove at a specific index:

local removed = table.remove(colors, 1)

After removing elements, the remaining elements shift so that the indexes stay continuous from 1 to the last element.

To find how many elements are in a list style table, Lua lets you use the length operator:

local count = #colors

This works best when your table uses indexes from 1 to n without gaps.

Important rule: The length operator #t is reliable only for list style tables where indexes go from 1 to n without missing numbers. If you skip indexes, #t may not give the result you expect.

Tables as Dictionaries and Maps

When you use non numeric keys, like strings, a table acts like a dictionary or map. It lets you associate a key with a value.

For example, you can map item names to their prices:

local itemPrices = {
    Potion = 50,
    Sword = 200,
    Shield = 150
}
local swordPrice = itemPrices.Sword

You can add more entries later:

itemPrices.Bow = 180
itemPrices["Magic Wand"] = 500

Dot syntax only works when the key is a simple name without spaces or special characters. For keys like "Magic Wand", you must use square brackets and a string.

If you assign nil to a key, you remove that entry from the table:

itemPrices.Shield = nil

After this, itemPrices.Shield will read as nil, which means the key is no longer stored in the table.

Mixed Tables: Combining Lists and Named Fields

Lua allows you to mix both styles in a single table. This is common in Roblox scripting.

For example:

local enemy = {
    Name = "Slime",
    Health = 30,
    100,
    200,
    300
}

In this example:

enemy.Name is "Slime".

enemy.Health is 30.

enemy[1] is 100.

enemy[2] is 200.

enemy[3] is 300.

You can use a table like this to store both properties and a list of values. When you mix styles, be clear about which parts are list indices and which parts are named fields so your code stays readable.

Nested Tables

Tables can contain other tables as values. This lets you build structured data.

For example, a table that holds positions as {x, y, z}:

local checkpoints = {
    {x = 0, y = 5, z = 0},
    {x = 10, y = 5, z = 0},
    {x = 20, y = 5, z = 0}
}

Here checkpoints[1] is a table, and checkpoints[1].x is 0.

You can also nest tables with named keys:

local playerProfile = {
    Name = "Alex",
    Stats = {
        Level = 5,
        Experience = 120,
        Coins = 300
    }
}
local level = playerProfile.Stats.Level

Nested tables are very useful when you want to group related data, such as player stats, inventory, or configuration settings, into a clear structure.

Copying and Referencing Tables

Variables that hold tables do not store the table itself. They store a reference to the table. If you assign one table variable to another, both variables refer to the same table.

local a = {1, 2, 3}
local b = a
b[1] = 10
print(a[1])

This prints 10 because a and b point to the same table.

If you want a separate copy, you must copy the values yourself:

local a = {1, 2, 3}
local b = {}
for i = 1, #a do
    b[i] = a[i]
end
b[1] = 10
print(a[1])

Now a[1] is still 1 because b is an independent table.

Important rule: Assigning one table variable to another does not create a new table. Both variables point to the same underlying table until you explicitly create and fill a new one.

Using Tables in Simple Roblox Style Data

To connect tables to the way you will use them in games, you can imagine a basic inventory structure. For example:

local inventory = {
    "Sword",
    "Potion",
    "Shield"
}
local itemCounts = {
    Sword = 1,
    Potion = 3,
    Shield = 1
}

inventory acts like an ordered list of items, while itemCounts lets you quickly look up how many of each item the player has. This pattern of combining a list table with a dictionary table appears often in game code.

Another simple pattern is a configuration table:

local settings = {
    MusicOn = true,
    Volume = 0.5,
    Difficulty = "Normal"
}

These examples prepare you for later chapters where tables will hold game data such as stats, shop items, power ups, and more.

Summary of Key Table Ideas

Tables can act as lists when you use numeric keys starting from 1.

Tables can act as dictionaries when you use names or strings as keys.

You can add or change entries simply by assigning to keys, and remove them by assigning nil.

The length operator # is useful when your table is a clean list without gaps.

Tables can contain tables, which lets you represent complex game data.

Variables store references to tables, not copies, so assignment shares the same table unless you manually copy the contents.

Views: 23

Comments

Please login to add a comment.

Don't have an account? Register now!