Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
Lua Tables

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.
  [4273] Dot or Colon separator between table name and member in Lua - what is the difference? - (2014-05-06)
  [4248] Metatables, Metamethods, classes and objects in Lua - (2014-03-18)
  [3694] Special __ methods you can use in Lua metatables - (2012-04-12)
  [2703] Lua Metatables - (2010-04-02)
  [2699] Lua tables - they are everything - (2010-03-30)
  [2499] ourdog is Greyhound, Staffie and Ginger Cake - (2009-11-09)
  [2346] The indexed and hashed parts of a Lua table - (2009-08-10)
  [1742] Lua - Table elements v table as a whole - (2008-08-07)
  [1697] Sorting in lua - specifying your own sort routine - (2008-07-05)


Back to
Learning to Program in Lua - public / open training course / class
Previous and next
or
Horse's mouth home
Forward to
Press Release - Museum to explore the story of Melksham
Some other Articles
Then and now pictures of Melksham - on show through the summer
The future needs for rail services to Melksham - change needed; current service an insult
Using Lua tables as objects
Press Release - Museum to explore the story of Melksham
Lua Tables
Learning to Program in Lua - public / open training course / class
Bank Holiday Monday, so it was pouring with rain.
Walking by the wiver
Naming blocks of code, structures and Object Orientation - efficient coding in manageable chunks
Melksham ATC - freedom of the town
4310 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87 at 50 posts per page


This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/3725_Lua-Tables.html • PAGE BUILT: Thu Sep 18 15:30:25 2014 • BUILD SYSTEM: WomanWithCat