Overview

In this tutorial we will learn about tables in luau programming language, and how they are being used to create arrays and dictionaries.

Tables can store large number of data items. They can take two kind of forms: arrays or dictionaries. If they are indexed with integers then they are called arrays, if indexes should be of other kind of type then they are called dictionaries. By using indexing term, I mean the way to access table data, for example tab[1] = "1"; access table tab at index 1 and updates its value with “1”.

Arrays

Arrays are a kind of table which is indexed with integer indexes. The simplest example is:

local tab = {"item1" , 1, true, 3};

Values stored in an array can be of different types. Each value is separated with semicolon, but you can also use a colon: ; . To print its values use:

print(tab)

this will give following output:

{
  [1] = "item1",
  [2] = 1,
  [3] = true,
  [4] = 3
}

Those numbers in the brackets: [1], [2], .. are indexes of the values in the array. In luau, arrays are indexed starting from index 1. In other languages indexes start from 0. To print only first element from our array use: print(tab[1)); what will output: item1. You can also assign value from array to local variable:

local val = tab[1];

When you have an array you often want to iterate it to either find an element you are looking for or update all the elements. To do this use for loop:

local tab = {nil, 1, 2, 3, nil}
for k, v in pairs(tab) do
  print(`at {k} we have {v}`);
end

Will output:

at 2 we have 1
at 3 we have 2
at 4 we have 3

The interesting thing is that the first and last elements with nil value are omitted in output. Another form of iteration is:

for k=1, #tab do
  print(`at {k} we have {tab[k]}`);  
end

which will give following output:

at 1 we have nil
at 2 we have 1
at 3 we have 2
at 4 we have 3

As you can see, table length can be retrieved by prefixing table with hash sign : #tab.

There is a library called table which provides generic functions for table and array manipulation. Among other you can get a length of array with table.getn(tab)instead of #tab if you like.

Dictionaries

Arrays allow us only to index our collection with integer values, but what if you want to use string as an index? Then You should use a dictionary which is actually very similar to arrays. Its initialization looks as follows:

local dic = {
  nam = "John",
  ["nick name"] = "Flint", # [ and ] used because there is a space inside key name
  hp = 42
}

Then you can access dic collection with:

print(`{dic.name} {dic["nick name"]} has {dic.hp} hp`)

What will produce:

 John Flint has 42 hp

To iterate all the key/value pairs of our dictionary we can use the same for loop as used above for array iteration:

for k,v in pairs(dic) do
  print(`----- {k} => {v}`)
end

Above will produce:

----- hp => 42
----- name => John
----- nick name => Flint

Multi-dimensional table

Now suppose we want to have a collection of players. Each will have a name, nick and health points. The code below presents how to do this. It actually combines arrays with dictionaries. Array is the table which keeps subsequent dictionaries. Each dictionary represents one player:

local players = {}

function addPlayer(name, nick, hp)
  table.insert(players,
    {name = name,
      ["nick name"] = nick,
      hp = hp
    }
  )
end

addPlayer("mike", "pain", 123)
addPlayer("frank", "boss", 145)
addPlayer("marty", "gorion", 234)

for i,p in pairs(players) do
  for k, v in pairs(p) do
    print(`{i}# - {k} = {v}`)
  end
end

will output:

1# - nick name = pain
1# - name = mike
1# - hp = 123
2# - nick name = boss
2# - name = frank
2# - hp = 145
3# - nick name = gorion
3# - name = marty
3# - hp = 234

As you can see we have a double iteration, first at line 16 we iterate array, in variable i we have an index of array and in p we have a value at that index. This value is our person dictionary which we iterate in line 17, this time k is key and v is value of dictionary.

Its worth noting that when we iterate dictionary then we cannot assume order of this iteration. Order is dependent on the way collection is storing our data. To iterate dictionary in some specified order you can use code from : http://lua-users.org/wiki/SortedIteration

Functions are values

Tables can store as values also functions, which is very useful in handling various events:

local actionsDict = {
  onKill = function(name)
    print(`{name} was killed`)
  end,
  onRebirth = function(name)
    print(`{name} was rebirthed`)
  end,
}

actionsDict.onKill("mike")
actionsDict.onRebirth("john")

produces:

mike was killed
john was rebirthed
Tagged:

Leave a Reply

Your email address will not be published. Required fields are marked *