KAHIBARO Bookshelves
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: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Introduction to Roblox & Game Design Basics
    • ☰ 1.1. Introduction to Roblox
      • ☰ 1.1.1. What is Roblox
        • ☰ 1.1.2. How Roblox games work
          • ☰ 1.1.3. Examples of successful Roblox games
            • ☰ 1.1.4. Installing and navigating Roblox Studio
              • ☰ 1.1.5. Understanding the Roblox ecosystem
              • ☰ 1.2. Introduction to Game Design
                • ☰ 1.2.1. What makes a game fun
                  • ☰ 1.2.2. Core game loops
                    • ☰ 1.2.3. Player motivation
                      • ☰ 1.2.4. Game genres on Roblox
                        • ☰ 1.2.5. Single-player vs multiplayer design
                        • ☰ 1.3. Getting Started with Roblox Studio
                          • ☰ 1.3.1. The interface (Explorer, Properties, Toolbox)
                            • ☰ 1.3.2. Parts and basic objects
                              • ☰ 1.3.3. Moving, scaling, rotating objects
                                • ☰ 1.3.4. Anchoring and collisions
                                  • ☰ 1.3.5. Basic lighting
                                • ☰ 2. Lua Programming Fundamentals
                                  • ☰ 2.1. Introduction to Lua
                                    • ☰ 2.1.1. What is Lua
                                      • ☰ 2.1.2. Variables
                                        • ☰ 2.1.3. Data types
                                          • ☰ 2.1.4. Tables
                                            • ☰ 2.1.5. Comments and good coding style
                                            • ☰ 2.2. Control Structures
                                              • ☰ 2.2.1. If statements
                                                • ☰ 2.2.2. Loops (for, while)
                                                  • ☰ 2.2.3. Functions
                                                    • ☰ 2.2.4. Scope
                                                    • ☰ 2.3. Roblox-Specific Scripting
                                                      • ☰ 2.3.1. Scripts vs LocalScripts
                                                        • ☰ 2.3.2. The Workspace
                                                          • ☰ 2.3.3. Events (Touched, Clicked)
                                                            • ☰ 2.3.4. Connecting functions to events
                                                          • ☰ 3. Building Your First Game
                                                            • ☰ 3.1. Creating a Simple Obby (Obstacle Course)
                                                              • ☰ 3.1.1. Designing levels
                                                                • ☰ 3.1.2. Kill bricks
                                                                  • ☰ 3.1.3. Checkpoints
                                                                    • ☰ 3.1.4. Spawn points
                                                                      • ☰ 3.1.5. Win conditions
                                                                      • ☰ 3.2. Adding UI
                                                                        • ☰ 3.2.1. ScreenGui
                                                                          • ☰ 3.2.2. Buttons
                                                                            • ☰ 3.2.3. Text labels
                                                                              • ☰ 3.2.4. Updating UI with scripts
                                                                                • ☰ 3.2.5. Creating a main menu
                                                                              • ☰ 4. Game Systems & Mechanics
                                                                                • ☰ 4.1. Player Systems
                                                                                  • ☰ 4.1.1. Health system
                                                                                    • ☰ 4.1.2. Damage system
                                                                                      • ☰ 4.1.3. Leaderboards
                                                                                        • ☰ 4.1.4. Player stats
                                                                                          • ☰ 4.1.5. Saving player data (DataStore)
                                                                                          • ☰ 4.2. Game Mechanics
                                                                                            • ☰ 4.2.1. Coins and collectibles
                                                                                              • ☰ 4.2.2. Shop system
                                                                                                • ☰ 4.2.3. Inventory system
                                                                                                  • ☰ 4.2.4. Tool system
                                                                                                    • ☰ 4.2.5. Power-ups
                                                                                                    • ☰ 4.3. Multiplayer Mechanics
                                                                                                      • ☰ 4.3.1. RemoteEvents
                                                                                                        • ☰ 4.3.2. Server vs client
                                                                                                          • ☰ 4.3.3. Preventing exploits
                                                                                                            • ☰ 4.3.4. Synchronizing players
                                                                                                          • ☰ 5. Advanced Game Design
                                                                                                            • ☰ 5.1. Combat Systems
                                                                                                              • ☰ 5.1.1. Melee combat
                                                                                                                • ☰ 5.1.2. Ranged combat
                                                                                                                  • ☰ 5.1.3. Animations
                                                                                                                    • ☰ 5.1.4. Cooldowns
                                                                                                                      • ☰ 5.1.5. Hit detection
                                                                                                                      • ☰ 5.2. Advanced UI & UX
                                                                                                                        • ☰ 5.2.1. Polished menus
                                                                                                                          • ☰ 5.2.2. Animations in UI
                                                                                                                            • ☰ 5.2.3. Sound design
                                                                                                                              • ☰ 5.2.4. Feedback systems
                                                                                                                              • ☰ 5.3. Monetization
                                                                                                                                • ☰ 5.3.1. Game passes
                                                                                                                                  • ☰ 5.3.2. Developer products
                                                                                                                                    • ☰ 5.3.3. In-game currency
                                                                                                                                      • ☰ 5.3.4. Ethical monetization
                                                                                                                                    • ☰ 6. Polish, Optimization & Publishing
                                                                                                                                      • ☰ 6.1. Optimization
                                                                                                                                        • ☰ 6.1.1. Reducing lag
                                                                                                                                          • ☰ 6.1.2. Script optimization
                                                                                                                                            • ☰ 6.1.3. Asset management
                                                                                                                                              • ☰ 6.1.4. Performance testing
                                                                                                                                              • ☰ 6.2. Testing & Debugging
                                                                                                                                                • ☰ 6.2.1. Common scripting errors
                                                                                                                                                  • ☰ 6.2.2. Using output window
                                                                                                                                                    • ☰ 6.2.3. Play testing strategies
                                                                                                                                                    • ☰ 6.3. Publishing Your Game
                                                                                                                                                      • ☰ 6.3.1. Game settings
                                                                                                                                                        • ☰ 6.3.2. Thumbnails and icons
                                                                                                                                                          • ☰ 6.3.3. Writing descriptions
                                                                                                                                                            • ☰ 6.3.4. Updating your game
                                                                                                                                                          • ☰ 7. Capstone Projects
                                                                                                                                                            • ☰ 7.1. Obby Game Project
                                                                                                                                                              • ☰ 7.1.1. Build a complete obstacle course game
                                                                                                                                                              • ☰ 7.2. Simulator Game Project
                                                                                                                                                                • ☰ 7.2.1. Create a clicker or simulator-style game
                                                                                                                                                                • ☰ 7.3. Multiplayer Combat Game Project
                                                                                                                                                                  • ☰ 7.3.1. Build a small PvP arena game
                                                                                                                                                                • ☰ 8. Bonus Topics
                                                                                                                                                                  • ☰ 8.1. Building a Tycoon Game
                                                                                                                                                                    • ☰ 8.2. Building a Tower Defense Game
                                                                                                                                                                      • ☰ 8.3. Creating Custom Animations
                                                                                                                                                                        • ☰ 8.4. Scripting NPC AI
                                                                                                                                                                          • ☰ 8.5. Advanced Physics Systems