12.7 Functions as table members

As we have already learnt before functions in Hollywood are just variables of the type "function". Therefore, you can use them everywhere where you can use variables. This includes tables. You can store functions just like normal strings or values inside a table and call them from there. Let us look at an example:

 
mathlib = {}  ; create an empty table

Function mathlib.add(a, b)
    Return(a + b)
EndFunction

Function mathlib.sub(a, b)
    Return(a - b)
EndFunction

Function mathlib.mul(a, b)
    Return(a * b)
EndFunction

Function mathlib.div(a, b)
    Return(a / b)
EndFunction

a = mathlib.mul(5, 10)  ; a receives the value 50

The table mathlib contains four functions now that can be called from it. Of course, we could also declare the functions during the initialization of the table. This would look like the following:

 
mathlib = {add = Function(a, b) Return(a + b) EndFunction,
           sub = Function(a, b) Return(a - b) EndFunction,
           mul = Function(a, b) Return(a * b) EndFunction,
           div = Function(a, b) Return(a / b) EndFunction}
a = mathlib.mul(5, 10)  ; a receives the value 50

This code does the very same as the code above but is more compact. Functions inside a table are also often refered to as "methods". This is a term from the object-oriented programming world.


Show TOC