Main Content

Towards Object Oriented Programming in Lua

Archive - Originally posted on "The Horse's Mouth" - 2008-06-30 06:26:15 - Graham Ellis

I've spent a lot of the weekend working on our Lua course ... and for those of you new to this language I'll be sharing a few snippets with you here on "The Horse's Mouth" over coming weeks. Today, I've got a short section which starts to introduce how you can do OO programming in Lua. The section of notes goes on to cover all the OO classics such as Encapsulation, Polymorphism and Inheritance and the course examples for this module are online via here

In Lua, we can keep functions in a table too, and we can bind a series of "metamethods" to a table which give it additional properties We also have syntactic sugar to make the new structures look and run sweetly. All of which leads to an effective Object Oriented capability in Lua, although without the classic keywords "class", "method", "private" etc.

Here are some of the basics - the use of the "." operator, and the storage of a piece of code as a first class function alongside the data.

stuff = {}
 
stuff["john"] = 14
stuff.dick = 24
function stuff.henry(value)
  return value * 2
  end
 
print (stuff.john)
print (stuff["dick"])
print (stuff.henry(16))
 
print (stuff["john"])


If you're trying to work out the difference between the "." operator and the use of a subscript in square brackets ... don't. They mean the same thing!

Here's how that program runs:

[trainee@easterton u107]$ lua dibdab
14
24
32
14
24
34
[trainee@easterton u107]$