"In Lua, function names are first class variables." Ok - so what does that mean?
At the most direct / simplest, it means that a function can be stored in a variable - so that you can write
function oik()
print ("does the real work!")
end
and then
action = oik
action()
to run the function via another variable ....
"So what?" you may ask.
It means that you can set up a series of functions ... and then a series of tables each containing the data about a particular (in my example) person, and within the table have a member variable that defines which particular function is run at a certain time.
By, in turn, storing those other tables into a table of people, it means you can then write a loop which processes data for each person, and which takes a slightly different action depending on which particular function (logic) you have referenced within each table object.
One you've got this set up ... the resultant code can be really elegant ... from a table called
team as your team of people ...
quay,bollard = next(team, nil)
while quay do
print (quay,bollard["name"],
bollard["approach"](oik),
bollard["age"],"\n")
quay,bollard = next(team, quay)
end
... and different logic will be run from the "approach" member depending on what approach you have defined for that particular member.
This is a powerful technique where you have a number of things (members) each of which may have slightly different logic applied to them - in fact (although I have avoided the words so far) it's an excellent application of Object Oriented principles. You have
• Each table within the master table being an
object
• Code that varies depending on the object being handled (
polymorphism)
• Common logic only being defined once, with extra added as necessary to specific objects (
inheritance)
• The ability to add in extra types (
classes) without having to rewrite the main logic in any way
Complete example at
this page(written 2008-08-07 07:55:19)
Associated topics are indexed under
U106 - Lua - Functions.U107 - Object Orientation - the Lua way
Some other Articles
Who is watching you?London for the visitor, for freeMoodle, Drupal, Django (and Rails)Lua examples, Lua CoursesFirst class functions in Lua lead to powerful OO facilitiesLua - Table elements v table as a wholeAge ConcernVertical LondonBath, Snake or Nag?Clean code, jump free (Example in Lua)