Main Content

Tables with values and code in Lua - looks like an object?

Archive - Originally posted on "The Horse's Mouth" - 2015-11-05 12:09:13 - Graham Ellis

In Lua, we can use variables to hold both data and code, and we can use tables to hold groups of values (numbers and strings) and code assiciated with those variables too. A new example - [here] on our web site - shows how I can define such a table:

  south = {cars=3,seats=78,time="06:38",destiny="Southampton"}

add a function (code) to it:

  function capacity(of)
    local peeps = math.floor(of.cars * of.seats * 1.4)
    return peeps
  end


  south.getCapacity = capacity

I can then run that code on the data using
  takes = south.getCapacity(south)
or
  takes = south:getCapacity()

The real gains start to come when I produce a whole table of servives, perhaps of different types (trains and buses) with differing code to work out the capacity. The need for "if" and "else" type coding in the getCapacity loop melts away:

  for _,service in ipairs(services) do
    print("Can carry " .. service:getCapacity() .. " to " .. service.destiny)
  end


From our Learning to program in Lua course, running this week, again next week, and available every 2 months next year. Check [here] for the next dates.