12.9 Methods

It is also possible to use Hollywood for object-oriented programming. Hollywood does not have the concept of class but you can easily emulate the behaviour using tables and metatables. One thing that is important for object-oriented programming is that object functions usually receive a handle to themselve as the first parameter. This parameter is usually called self or this. Of course, you can emulate this behaviour by simply declaring a self or this parameter in your function and passing to it the object whenever you call the function, but you can also use a special syntax for object-oriented programming that Hollywood offers.

If you declare your functions using the colon operator Hollywood will automatically initialize a hidden self parameter for you. You do not have to declare it explicitly. If you use the colon syntax, it is always there. Functions that are declared using the colon syntax are called methods because they are dependent on a root object.

Here is a simple example of a methods in Hollywood:

cart = {items = {}, numitems = 0}

Function cart:AddItem(n$, p)
    self.items[self.numitems] = {name = n$, price = p}
    self.numitems = self.numitems + 1

Function cart:RemoveItem(n$)
    For Local k = 0 To self.numitems - 1
       If self.items[k].name = n$
         RemoveItem(self.items, k)
         self.numitems = self.numitems - 1

Function cart:CheckOut()
    Local total = 0

    For Local k = 0 To self.numitems - 1
       NPrint(self.items[k].name, self.items[k].price)
       total = total + self.items[k].price

    NPrint("Your total is", total)

cart:AddItem("DVD", 10)
cart:AddItem("Blizzard PPC", 1000)
cart:AddItem("AAA Chipset", 100000)
cart:AddItem("68070", 500)
cart:RemoveItem("Blizzard PPC")

The code above creates a simple class that represents a cart. The class has three methods: Add item, remove item, and check out. Furthermore, it has two properties: A table containing a list of all elements in the cart, and a count value that contains how many elements are currently in the cart. You can see that each of the three methods works with a self variable which has not been declared. This is because all methods have been declared using the colon operator and thus Hollywood will always pass a the self parameter to them automatically.

Of course there is more much more to object-oriented programming than covered in this brief excursion. Going into the depths of OOP (inheritance, multiple inheritance, privacy, etc.) would be too much for this guide, but it is all possible with Hollywood tables and metatables. If you are interested in learning more about this topic, you should consult a book about the Lua programming language because Hollywood uses a Lua kernel. For example, the book "Programming in Lua (second edition)" by Roberto Ierusalimschy has an extensive chapter about OOP in Lua, which you usually can adapt straight into Hollywood code.

Show TOC