Lua's Tables are its "collection" variables - in other words, they hold a whole series of other variables, which can be looked up by a key of some sort.
I can set up a table like this:
occupancy = {2,5,5,3,2}
which will set up a Lua variable called "occupancy" with five members, numbered 1 to 5, with values 2, 5, 5, 3 and 2.
I can then reference the values by their position, using square brackets:
print (occupancy[4])
will give me the result
3 since the fourth element - element number 4 - contains the value 3.
I can change values, for example:
occupancy[4] = occupancy[4] + 2
and even extend the table by adding another element onto the end
occupancy[6] = 4
I can use a variable to refer to a the position number in a table too - thus:
k=2
print (occupancy[k])
will give me the result
5 as that's the value in the second position (position number 2) of the table.
By using a # sign in front of a table, I can refer to the number of elements in a table - thus I can write a generic piece of code to extend a table:
occupancy[#occupancy + 1] = 2
and I can loop through every member of a table such as the one in the example I have used so far using a loop:
roomnights = 0
for k = 1,#occupancy do
roomnights = roomnights + occupancy[k]
end
print ("You have a total occupancy of "..roomnights.." room nights")
And I can set up an empty table like this:
another = {}
In the example above, I've only stored numbers in my table (in Lua, all numbers are actually double precision floats, so there's no "integer v real" question to address). But I'm not limited to that - I can store anything that I can store into a regular variable into a table, including:
• a number
• a string of text
• a function (a callable piece of code)
• another table
and I can even store different types of data into different elements of the same table.
There's an example from the course notes - showing what I've talked about above -
[here].
So far, I have used position
numbers starting from 1 within my example tables - and so it's been rather like a
list if you're familiar with Perl, Python or Tcl, like an
array if you're familiar with C or PHP, or like a
vector if you're familiar with C++ or Java.
But in Lua I can go further and use
named elements in my table. That will mean I can compare with a
hash in Perl or Java, an
associative array in PHP, a
dict in Python, an
array or a
dict in Tcl, etc. Let's see how that works:
Setting up a table with named members:
roles = {chair = "Sion", treasurer = "Chris", secretary = "Phil"}
adding on more:
roles["vicechair"] = "Peter"
roles["press and publicity"] = "Graham"
I can then access individual members using the key name:
print (roles["secretary"])
or indeed using a variable which contains the role name:
contact = "press and publicity"
print (roles[contact])
If I re-use a key as I assign a value, I'm replacing a member (cell) of my table. If I give a new key, then that will add a new member to my table:
roles["supporter"] = "Dominic" -- adds new then ...
roles["supporter"] = "Roger" -- replaces that value
When I had numbered elements I could easily loop through my table, but now that the elements are named, I can't simply write a loop in quite the same way as the names are unpredictable. However, I'm provided with a function in the Lua standard implementation called
pairs which lets me loop through all the key / value pairs of a table so that I can perform an action on each of them in turn:
for k,v in pairs(roles) do
print (v .. " is in the role " .. k)
end
results:
Sion is in the role chair
Graham is in the role press and publicity
Phil is in the role secretary
Roger is in the role supporter
Peter is in the role vicechair
Chris is in the role treasurer
You'll notice that the order is unpredicatable (and certainly not useful) and this is because a "hashing algorithm" is used, which makes it very fast to access individual elements, but impossible to sort them directly into any form or order.
I can delete individual members by setting them to
nil, and I can delete an entire table by setting in to
nil.
An alternative notation for table members allows me to replace the pair of square brackets for a named member with a dot - you'll see this commonly used, and forming an object-like approach in the process if you're familiar with object oriented programming. Thus
print (roles["vicechair"])
print (roles.vicechair)
use different syntax to mean exactly the same thing.
There's an example of a table with named members from our course material
[here].
On yesterday's
Lua Programming Course, this was the point we got to in tables. There's an extra colon notation to cover yet, and the whole big subject of
metatables ... something for me to come back to later today - or you can find some examples already from the course notes and previous courses via
[here].
The final example from yesterday is
[here]. We put together string handling, file handling and tables to produce a useful piece of code which reads the records in a file, etracts some key / value pairs from selected columns, and stores all of the pairs which meet certain criteria. Once the table has been set up, our demonstration simply prints out the whole table, but we could go on and extend the application to do much more. In fact, I'm sure we'll start today by sorting the results - it's not directly possible, but indirectly it's very easy indeed when you know how ;-)
(written 2012-05-10, updated 2012-05-12)
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
U105 - Lua - Tables and the table library. [1697] Sorting in lua - specifying your own sort routine - (2008-07-05)
[1742] Lua - Table elements v table as a whole - (2008-08-07)
[2346] The indexed and hashed parts of a Lua table - (2009-08-10)
[2499] ourdog is Greyhound, Staffie and Ginger Cake - (2009-11-09)
[2699] Lua tables - they are everything - (2010-03-30)
[2703] Lua Metatables - (2010-04-02)
[3694] Special __ methods you can use in Lua metatables - (2012-04-12)
[4248] Metatables, Metamethods, classes and objects in Lua - (2014-03-18)
[4273] Dot or Colon separator between table name and member in Lua - what is the difference? - (2014-05-06)
[4571] Lua - using modules to add your own utilities - (2015-11-04)
Some other Articles
Then and now pictures of Melksham - on show through the summerThe future needs for rail services to Melksham - change needed; current service an insultUsing Lua tables as objectsPress Release - Museum to explore the story of MelkshamLua TablesLearning to Program in Lua - public / open training course / classBank Holiday Monday, so it was pouring with rain.Walking by the wiverNaming blocks of code, structures and Object Orientation - efficient coding in manageable chunksMelksham ATC - freedom of the town