How does tables work?

I have a problem in learning tables, I’ve watched countless videos but I still get confused.

3 Likes

Tables are ways of storing multiple values.
In an array, there are two items to every field (index and value). Index is the position the value is in the table, indexes start at 1 on Roblox.

Initiating an empty table is as easy as:
local thisIsATable = {}

You can use tables to store values like this:
local thisIsATable = {"value1","value2"}

If you wanted to index an array, you would need to do this: local var = thisIsATable[index]
You can replace index with any number, as long as it’s within the amount of values in the array. In this case, there are only 2 and so, if I wanted to get value1, I could do: print(thisIsATable[1])

You can have custom indexes, like this (although this is now a dictionary):

local tab = {
	["index"] = "value"
}

In this case, “index” is the index and “value” is the value. Thus, I could do print(tab["index"]) to get the value. It would output ‘value’ (no quotations).

To iterate through an array, you can use a count-controlled loop (as there is a definite amount of number of items in an array, you’re not waiting for a condition)

for i,v in pairs(thisIsATable) do
	print(i,v)
end

This will print the index at each part in the array, as well as the values.
If we use this table: local thisIsATable = {"value1","value2"}
The output will look like this:

1 value1
2 value2

In terms of special table functions, there a few to choose from.
https://developer.roblox.com/en-us/api-reference/lua-docs/table/index.html

Pretty basic ones (might be the ones you use the most, depends on the context):
table.insert(tableNameHere, thingYouWantToAdd)
And
table.remove(tableNameHere, indexOfTheThingYouWantToRemove)
Note that the removing requires an index, and so you’d probably want to loop to find the value that matches your specific term (e.g. looping to find the word value2 in the table) and then get the index from it.

4 Likes
Here are some resources:

Well here would be some examples of tables:

--[[

    This script will make that when a player joins the game
     their name will be added to the Players Table.

]]--

local Player = game.Players.LocalPlayer
local Players = {}

game.Players.PlayerAdded:Connect(function(Player)
   table.insert(Players, Player.Name)
end)
1 Like