Tables as Arrays

System: Haiku, Windows, Linux, Mac

Lua tables have a dual nature of being both an array and an associative hash table. They are the basis of objects in the language. They can be used to make other data structures like linked lists and so on.

We are going to create a simple table, and most of the times we are going to use them as arrays, so let's work.



Now that we have created the table let's fill it with some data.

table ={1,2,3,4,5,8,7,9}


Now that we fill the table with data we must print it to the screen, and for that we use the EGSL command drawtext (), that accepts tree args.
We will pass the X position, the Y position and then the string with the first index of the table.

drawtext(0,0,"Table Index 1 = "..table[1])


And the result should look like this:



But we all have seen just the index one, what if I want to see the rest of the table? Well the manual way is doing by hand.

drawtext(0,0,"Table Index 1 = "..table[1])
drawtext(10,10,"Table Index 2 = "..table[2])
drawtext(20,20,"Table Index 3 = "..table[3])
drawtext(30,30,"Table Index 4 = "..table[4])

 



  See the all code for this part in the picture.



Well there is a better way of doing this and that is with a for loop, let's see first how to loop the all table without knowing the size of the table.

There is a way to see the length of the table and the way of doing that is by using the # sign, so if we want to print the size of the table we code this way.

drawtext(0,0,"Table Index 1 = "..#table)


And the result in our case is 8. See picture.



Now that we know how to run thru the table we are going to print the same thing before but this time must better and faster.

for i=1,#table do
    print("Table index "..i.." = "..table[i])
end


There are several ways of using tables, let's see some of the most used, we already did one way.

table={}

table[1] = "blue"
table[2] = "red"
table[3] = "yellow"
table[4] = "green"
table[5] = "purple"

drawtext(0,0,table[3]) -' it outputs yellow 

table={
    [2] = "red",
    [3] = "yellow",
    [4] = "green",
    [5] = "purple"
} 

Drawtext(0,0,table[3]) -' also yellow

table{
    "blue",
    "red",
    "yellow",
    "green",
    "purple"
} 

Drawtext(0,0,table[3])-' guess what? Yellow <br< 
Table={ "blue", "red", "yellow", "green", "purple" } 

drawtext(0,0,table[3]


And now the test:



And for the output we have the color?



As you can see all the ways are different but the result is the same, so it´s a matter of preference, this works very good as arrays, single arrays, to declare multiple arrays you have to do like the next piece of code, see it.

Multi dimension array.

for i = 0,99 do
    table[i] = {}
    for j = 0,2 do
        table[i][j] = 0
    end
end


Tables as Dictionaries

Ok, so now we will work with table as dictionaries, and for that the tables are a bit different from the previous, but this is nothing from the space unless you code a space shooting.

table{
    sky = "blue",
    grass = "green",
    water = "blue",
    lava = "red"
}

table.dirt="brown"


See how I have inserted in the table a new value called dirt?

Now we are going to test it to see if that works or I just invent that.



The result:



Well it seems to work, so as you see the tables are very flexible and powerful, but that's not all about them.

This way when you work with tables you can call them like:

table.dirt
or
table["dirt"]


both work the same way

Another way of inserting values into the table is using the keyword insert.

Example:

t={1,2,3,4,5,6}

table.insert(t,7) 

print(t[7])

 



As you can see above the table as six values and then we inserted a new one, this time the table as seven values and the number seven is also the number seven.

See the console.



Another way of inserting values inside a table is giving the key and value to it, basically is the same as above the difference is that we provide a key to the value we want.

Example:

t={1,2,3,4,5,6,}

table.insert(t,1,7) 

print(#t)
print(t[1])

 



And the output:



The first key of the table as the value one, but after we insert the new one it stays with number seven.

Now that we don't need any more the number that we have inserted we must remove it, but how?

Easy, let's use the key remove.

t={1,2,3,4,5,6,}

t={1,2,3,4,5,6,7} 

table.remove(t,7) 

print(#t)
print(t[7])

 



And the output:



Data Types

We can store additional tables, functions, and function references with the keys of a table, as well as the more common numbers and strings.

This time we are going to work with tables inside tables and to start we are going to see some examples, hand on.

people ={ { name="Bob", age=32, gender="male" },
    { name="Jane", age=29, gender="female" }}


Now that let us test it.



And the result:



There is no limit to how many tables you can store within other tables.

Another complex form of data you'll see stored within the keys of a table are functions and references to other functions. Here's an example of a reference to a function stored in the key of a table:

Example:

openwindow(200,200,0,"Tables Part I") 

local function helloWorld()
    drawtext(0,0,"Hello World")
end 

local functable = {name="bob",func=helloWorld} 

color(255,0,0) 

functable.func() 

sync()
inkey()
closewindow()

 



Result:



Another way of doing the same thing is:

Example:

local function helloWorld()
    drawtext(0,0,"Hello World")
end

local functable = { 100, 100, helloWorld, true } 

color(255,0,0) 
functable[3]()

 



The result:



As you can see the result is the same, so it's up to you how do you want to use them. <br<
Now for more complex stuff we are going to store not a key but an actual function inside a table, are you ready?

Ok let's code then.

Example:

local functable = { 100, 100, function()
drawtext( 0,0,"Hello World!");end,true} 

functable[3]() <- don't forget to put the () because we are calling a function. 


Each key within a table is no different than any other variable in Lua. You can store anything you want within it. That's the best way to look at it.

When tables start getting big and confusing, the best advice I can give is to just look at what's between the commas separately, as if it is on a line of code by itself. From there, your confusion should start clearing up.

Tables and Loops

One of the most common purposes of using tables over regular variables is the ability to "iterate" over the keys of a table with a loop.

Below is an example of how to iterate through a table with numerical keys:

Example:

local loops = {
    "blue",
    "red",
    "yellow",
    "green",
    "white",
    "purple"
} 

for i=1,#loops do
    print(loops[i] )
end

 



And the output is showed in the end of the IDE because it's an print statement.

See bellow:



What if your table has key names instead of numbers?

For that, we'll use the pairs() function (which returns two variables).

Let's do it.

local loops = {
    sky = "blue",
    grass = "green",
    water = "blue",
    lava = "red",
    dirt = "brown"
}
for key,value in pairs(loops) do     print( key, value ) end

 



Can you see the difference? Watch out the console output.



Cool isn't?

Another way of doing an itineration is to use the key ipairs().

Example:

t={1,2,3,4}
for i,v in ipairs(t) do
    print(i,v)
end

 



Result:



This operator doesn't work with dictionaries, only with numbers as keys, to use with names as keys you must use pairs() instead.

pairs() loops through each key and value pair in a table in an order that isn't guaranteed. ipairs() loops through each key and value pair by increasing the key by one each time, therefore it needs to be a numerically indexed table.

A simple way of doing the same thing and obtain the same result is using a built in function called foreach().
This will display all of the elements in a table, mixed or not.

Example:

tab = {1,2,3,4,5,6} 

table.foreach(tab,print)

 



Result:



To display only the index-values we must use the foreachi(), this one is deprecated in Lua 5.1.

To see more about tables you must seek in the official documentation.

To finish this tutorial I will Wright two more functions that are built in Lua, the sort() and the concat().

The sort() is used to put the values in a table by order, the same as a normal sort function do and the concat() is used to concatenate the elements of a table together to form a string.

Example:

tab = {3,5,1,4,2} 

table.sort(tab)
tab1=table.concat(tab,",") 

print(tab1)

 



Result:



Example of a concat() function:

tab = {3,5,1,4,2} 

tab1=table.concat(tab) 

print(tab1)

 



Result:



To understand better the tables code each example into the IDE and try it out, in the above example try to put in the concat() an "," to see what's going to happen, this function accepts also a range.

There are more complex stuff about tables but for now this will be the reference to ESGL.

Hope that you guys like it and enjoyed it as I did in making this tutorial.

Thanks Cvirus.

Tutorial By Cvirus
Made available by BeSly, the Haiku, BeOS and Zeta knowledge base.