Extremely Basic Question: {}

Hi there,
As someone who is relatively inexperienced in scripting, I often see these types of brackets, {}, being used often. I have looked on the API website and couldn’t really come up with anything conclusive so I am taking it to you guys to help me. All I want to know is:

  • What it is.
  • What it is used for.
  • How to use it properly.
    See, I often see {} brackets in ModuleScripts, Tween events and so on yet I never really understood what they are for. Any answers would be amazing!
    Thanks, Fusioncore21
8 Likes

That’s how you construct a table. Here’s the wiki page for tables:

6 Likes

as far as I know, {} can be used for lists of items, more known as, “tables”.
Here is an example

Table = {"I", "Like", "Doughnuts"}
print(Table[1]..Table[2]..Table[3]) -- prints ILikeDonuts     [no spaces]
2 Likes

{}, known as curly brackets, are used to create so called tables. Tables come in a couple of different shapes, but to put it short tables are essentially a lists.


How does it work?
Tables can be bit hard to explain in a single post like this, but I’ll try to explain to the best of my ability. There are a lot of guides around the web for the table datatypes, so if you’re confused it’s easy to find other resources.

local Item1 =  "One"
local Item2 =  "Two" 
local Item3 =  "Three" 

print(Item1) 
print(Item2) 
print(Item3) 

The code above works perfectly fine - it prints the three values to the output. However, code such as this will get messy at scale and it will become very hard to make quick changes. To clean up this code, let’s use tables!

local Items = {"One", "Two", "Three"} 

This type of Table is called an Array. Arrays are the most simple type of Table as they simply store values in lists which can later be accessed by a numerical index. Each value (sometimes known as key) is seperated by a comma.

To aquire the values we have inside of our array, we need to index it. Indexing an array in lua looks like this:

local BestItem = Items[2] 

We begin by typing out the name of the array we have saved and then we follow it with 2 square brackets. Inside of the brackets we can enter a number, this number corresponds to a position inside of our array. For example:

local Gifts = {"Coal", "Fish", "Premium"} 
--                1         2      3

local SelectedGift = Gifts[3]
print(SelectedGift) --Prints: Premium

With this in mind, we can create a more effective version of the code we began with!

local Items = {"One", "Two", "Three"} 

for i = 1, #Items, 1 do -- Use # to get the length of our array 
    print(Items[i]) 
end

Keep in mind that you can save any type of value inside of a table. Strings, Numbers, more tables?! You got it!


Other types of tables
Arrays are only one of the different Tables you can create. Here’s a breif overview on the other types:

  • Dictonary: Works almost like arrays do. Every value begins with a determined key wrapped inside of square brackets. Instead of using numbers when indexing the table, you use the key!

      local Data = {
          ["Health"] = 421,
          ["Stamina"] = 12,
          ["Nickname"] = "Noobster"
      }
      
      print(Data["Stamina"]) -- Prints: 12
    
  • Array with keys: To be honest, I don’t know what this type if table is called. It works just like dictonaries do but with a couple twists. This type of table dosen’t have square brackets or double quotes around it, it’s just text! To index this type of table, use a dot instead of brackets. These tables are often used within Object Oriented Programming.

      local ToDo = { Important = "Sleep.", LuckyNumber = 13}
    
      print(ToDo.LuckyNumber) -- Prints: 13
    
  • Metatable: These work like the table type above, however, they can utilize so called metamethods to perform actions normal tables cannot. This type is more advanced than the ones above, we won’t be discussing it here.


Awesome! What can they be used for?
Tables are very useful for organizing your code. Instead of having 15 variables merely for funny Einstein quotes, use an array and store them all in just one!

Tables are often used within handling player data and long lists. Tables are also used for Object Oriented Programming if the form of ModuleScripts.


Further reading
I’m no teacher, so my explainations may be a bit confusing. Here’s a couple of useful resources on the Developer Hub you can use to learn more about tables:

24 Likes

Nobody here covered arrays which are the most important part of any serious project, but I’ll start from beginning.

Lua’s tables are just data containers. They are the same as hash tables in other languages, but that’s not exactly that important for beginners. In short, they are used to store values (any type) under indices (everything but booleans and nil).

To create a table, you use the curly brackets you mentioned, or table.create(). In fact, in vanilla Lua, all the libraries (table, string, math…) are tables.

local tab = {} --creates an empty table
local arr = {1,2,3} --creates an array table with 3 values
local arr = {[1]=1,[2]=2,[3]=3} --same as previous
local dict = {a="something",b="another thing"} --creates a dictionary
local dict = {["a"] ="something",["b"] ="another thing"} --same as previous
local arr = table.create(10,"a") --creates an array of size 10 filled with "a"

Tables are mutable and referenced. This means that you can change their values and assigning them to a different variable makes both variables hold the same table.

local tab = {} --creates a new table
local tabsame = tab --assigns the table to a different variable
tab[1]="test" --adds value test to index [1]

So what are the practical uses tables can do that variables can’t? Well, alongside what everyone else here said, as tables can contain any value, that means they can also contain other tables. That is called a multidimensional table. This means that you can create easily grids that are easily manipulated.

--this creates a 10x10 grid
local tabx = {}
for x=1,10 do
    local taby = {}; tabx[x]=taby
    for y=1,10 do
        taby[y]=0
    end
end
print(tabx[2][5])

There are multiple ways to iterate over all values within a table. If you want the best performance and your table is an array, you should use a for loop; otherwise, you can use a pairs(tab), ipairs(tab) and in next, tab.

local tab = {1,2,3,["a"]="a"}

for i=1,#tab do -- # is an operator which returns the length of your table. Though not the dictionary part
    print(tab[i])
end
--1,2,3. "a" is never reached since its index isn't a number.

for i,v in next, tab do
    print(tab[i])
end
--1,2,3,a. It will reach all of the values

for i,v in pairs(tab) do
    print(tab[i])
end
--same as previous

for i,v in ipairs(tab) do
    print(tab[i])
end
--close to the first one. It will also print 1,2,3, but not "a"
4 Likes

Explaining tables as a general concept is more helpful than describing a specific subset of tables that aren’t even strictly defined.

1 Like

Though they do work differently for many cases. Most beginners end up getting confused by # and table.len() as they only count the array component of the tables, completely ignoring the hash part.

He pinned out that he wanted to know what they can be used for and how to do it properly and that is exactly what I answered. Multi-dimensional tables are rarely explained in most Lua tutorials, but can easily solve most troubles. If you know a bit more, you can easily make that much faster using row/column major order.

1 Like

What It Is

{} Curly brackets (some people refer to as “curly braces”). They are used for something in Lua called “tables”. These store multiple pieces of information about anything really. Such information can range from a simple string to an entire function. To separate this information, you must use commas.

For example, this is a table:

 local Table = {"info1", "info2", "info3"}

--tables can also be written vertically, for the sake of readability (does nothing different)
local verticleTable = {
    "info1",
    "info2",
    "info3"
}

If we try to print this, the output’s going to spit out a Hexademical memory address (which you don’t need to know in order to understand tables).

Something like (I am not an expert in HEX):

--FF020BA10

To extract information from a table, we need to know its position. Because “Info1” is the first piece of information, its place (or index) is 1. The index of “Info2” is 2, “Info3” is 3.

So, to actually reference and print one of these strings, you must write this:

local num1 = Table[1] --or [2] or [3] or so on...
print(num1) --output: info1

--if it was
local num2 = Table[2]
print(num2) --output: info2

If you want to index something in a table without using numbers, then you can create a dictionary. A dictionary (in Lua, at least) is a table that has its own index and values (values are what is for each index, i.e. “info1” or “info2”).

Here’s a simple dictionary (you would want this to be verticle because it’s easier to read):

local dictionary = {
   "String" = "Any character that is within a single or double quotation mark like this itself.",
   "Roblox" = "A massive multi-player platform off of which developers can create their own games!",
   "Catalog" = "A section in Roblox where you can buy virtual items for your avatar."
}

MAKE SURE you don’t forget to use commas to separate values!
There, we have a nice dictionary. So, to print something out in this, you can simply use the string to index its value.

local defString = dictionary["String"]
print(defString)
--[[output: Any  character that is within a single or double quotation mark like this itself.]]

Additionally, you can do operations with tables. You can add and remove values later on using a script. Or, you can unpack a table to spread the contents of a table out as arguments.

Unpacking in action:

local nums = {2, 3214, 34, 12}
local Max = math.max(1, unpack(nums)) --it would be math.max(1, 2, 3214, 34, 12)
print(Max) --3214

I cannot explain and show everything that you can do with tables, so for that you can visit the Developer Hub table page.

I hope that helps!

1 Like

These two are exactly the same, the second part is just syntax sugar that makes it easier to use. Table.Key is the same as Table['Key']. In addition, the syntax sugar style wouldn’t work if the key had a space in it ( Table.Key With Spaces), so you would need to do Table['Key With Spaces']. This also applies for non-string keys like bools or objects – you can’t do Table.true but you can do Table[true] (it would think Table.true is a string key).

Metatables in a nutshell let you extend the functionality of tables. Let’s say you wanted to be able to multiply a table, you give it a metatable with a __mul() function that will be called when the table is multiplied with something else using the * symbol. But definitely get a handle on basic tables before you start using these.

2 Likes

Seeing that you’re newer to scripting I think that some of the above replies may be slightly over/under complicated so I kind of want to add on.

Curly brackets in lua are used to define a “table.” A table is just a list of data with different identifiers (indexes) to match to different values. It can be a simple list of items (an array) or one with more complicated indexes (a dictionary).

Tables are used almost everywhere. They are a fundamental piece of all programming languages (and vary a lot from language to language!) Modules use them to keep functions and properties. They are used by most Roblox instances. For example, there is a function called GetChildren which returns a table (which is an array) that has all of that instance’s child instances.

Using a table to store data is thankfully pretty simple! There are a ton of ways to store information in table, but here are some common ones:

local tbl = {} -- tbl is short for table
tbl[index] = value
tbl.stringIndex = value -- Equivalent to tbl["stringIndex"]

function tbl.func() -- Equivalent to tbl.func = function()...
	-- Some code!
end
function tbl:func2() -- Equivalent to tbl.func = function(self)...
	-- Some other code
end

And here are the same ways to access that information:

print(tbl[index]) -- Will output the value in the table at the index
print(tbl.stringIndex) -- Equivalent to tbl["stringIndex"]

tbl.func() -- Equivalent to the stringIndex above but we just call the value!
tbl:func2() -- A bit different. The colon just adds an extra argument! The line below is exactly the same.
tbl.func2(tbl) -- This is because when calling or defining functions using a : it adds an extra argument. This lets you do some cool stuff

Fun fact: Roblox instances all use the same function! That’s why you need to call them with a :!

local getChildren = game.GetChildren

getChildren(workspace) -- Returns the children of the workspace! Equivalent to calling workspace:GetChildren() since game.GetChildren and workspace.GetChildren are actually literally the same exact function!

Finally, you can “loop” through tables in a lot of ways. The two primary ways are using ipairs and pairs loops. These are a bit faster than some other methods and I’d recommend them! There are examples of other loops and table length used above.

local tbl = {["dictionary"] = "test", "a", "b", "c", [5] = "d"}
-- Notice that c is the third item and I skip over the fourth!
-- Arrays in lua aren't allowed to have gaps so the loop will stop!
for index, value in ipairs(tbl) do -- ipairs (I believe this stands for individual pairs) is used for arrays! This is basically equivalent to the for loop shown in the above post!
	print(index, value) -- Will print the index and the value!
end
-- The above loop will output this:
-- 1 a
-- 2 b
-- 3 c

-- Pairs is similar but it allows for dictionaries!
for index, value in pairs(tbl) do -- Notice that the table I use is still the same!
	print(index, value)
end
-- The above loop should print:
-- 1 a
-- 2 b
-- 3 c
-- 5 d
-- dictionary test
-- That's because it also allows for dictionary keys!

I hope that this helps you understand what a table is and how its used! And as others have said as well, we’re all happy to answer questions you might have if any of us made something unclear or confusing.

Alright, so thank you for all your help on this subject, it has been incredibly resourceful to read all of your replies.
One final thing, say we had a part and we had a table with all the transformations inside of it, what would be a quick why to translate those changes to the part, without manually using a dictionary-key system? Would you use a for loop to go through each value?

1 Like

Yes, a loop would be the simplest way.

local transformation = CFrame.new()
for _, t in pairs(transformations)
    transformation = transformation * t
end
part.CFrame = part.CFrame * transformation

Use ipairs instead if it’s guaranteed to be a regular well-defined array.
Put the translation part into the loop if you need to do operations after each of the translations.
Use + instead if it’s just Vector3s.

1 Like