# Table & Dictionary

In this section, we will be discussing tables and dictionaries. A table can be used to store data inside and a dictionary is a key with a value in the table.

## CREATING A TABLE

First, we are going to make a variable and we gonna store curly brackets in that variable

```lua
local myTable = {} -- Create a new empty table
```

### PUTTING DATA INTO THE TABLE

Now, we are going to put some data into a table. In this example, I will be using string.

```lua
local myTable = {
     'Banana';
     'Apple';
     'Orange';
}
```

### GETTING DATA INSIDE THE TABLE

To get the data inside the table, we have to index it out by getting the table, using the square brackets, and indexing it out with numbers.

```lua
local myTable = {
     'Banana'; -- 1
     'Apple'; -- 2
     'Orange'; -- 3
}

print(myTable[1]) -- This will print out Banana
```

### GETTING THE TABLE LENGTH

To get the amounts of how many arrays are in the table. We can use the # symbol to see the number of arrays in the table.

{% hint style="warning" %}
NOTE: The # symbol only gets arrays, not dictionaries. Please remember if you want to know how to get dictionaries and array amounts in the table. You can see example 2 below.

#### Example 1:&#x20;

```lua
local myTable = {
	Fruit1 = 'Banana'; -- 1
	Fruit2 = 'Apple'; -- 2
	Fruit3 = 'Orange'; -- 3
}

print(#myTable]) -- This will print 0 because the table has no arrays.
```

#### Example 2:

```lua
local function getTableRealLength(tbl)
	local length = 0
	--- Learn how to use for loop in the "Loops" section.
	for _, v in pairs(tbl) do
		length += 1
	end

	return length
end

local myTable = {
	Fruit1 = 'Banana'; -- 1
	Fruit2 = 'Apple'; -- 2
	Fruit3 = 'Orange'; -- 3
	true,
	1,
	6,
	8,
}

local result = getTableRealLength(myTable)
print(result)
```

{% endhint %}

```lua
local myTable = {
	'Banana'; -- 1
	'Apple'; -- 2
	'Orange'; -- 3
}

print(#myTable) -- This will print 3 because there are 3 arrays in the table.
```

## CREATING A DICTIONARY

To make a dictionary we will create a new table.

```lua
local myDictionary = {}
```

### INSERTING KEYS

Now we will give the key a name and assign data to it.

{% hint style="warning" %}
When you **create a key with space** **or number** you must use square brackets and a string.
{% endhint %}

```lua
local myDictionary = {
     Fruit1 = 'Apple';
     Fruit2 = 'Orange';
     ['Best Fruit'] = 'Grapes'
}
```

### GETTING THE KEY DATA

Now, we can get the data by using the dictionary, using square brackets or a period, and then indexing the key name.

{% hint style="warning" %}
You can **use a period for non-space or non-number dictionary key names** but you have to **use square brackets for the key name with a number or space in its name.**
{% endhint %}

```lua
local myDictionary = {
     Fruit1 = 'Apple';
     Fruit2 = 'Orange';
     ['Best Fruit'] = 'Grapes'
}

print(myDictionary.Fruit1) -- Apple
print(myDictionary['Best Fruit']) -- Grapes
```
