Lua and classes are a little awkward, as there really is no such thing as classes in Lua. However, it is possible to demonstrate a class like behavior using tables.
Tables are a type of object, and since an instance of a class is also an object, we can use tables as if the language itself supported classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
local Triangle = { width = 0, height = 0 } function Triangle:set( fWidth, fHeight ) self.width = fWidth self.height = fHeight end function Triangle:get() return { width = self.width, height = self.height } end function Triangle:calculate() return self.width * self.height / 2 end function Triangle.print() print ( "width = " .. self.width .. ", height = " .. self.height ) end |
You can see that an object called “Triangle” is created and useful functions for it is also created. If we were to execute these functions:
1 2 3 4 |
Triangle.print() Triangle.set(10, 5) Triangle.print() print( "Triangle's area = " .. Triangle.calculate() ) |
Then the outputs become:
1 2 3 |
width = 0, height = 0 width = 10, height = 5 Triangle's area = 25 |
Note that instead of the period ‘.’, I used the colon ‘:’ to create the functions. This is to pass ‘self’ as the first parameter for object-oriented programming. In the case that I used a period to create the functions, the following commands would result in an error.
1 2 3 |
newTriangle = Triangle Triangle = nil newTriangle.print() |
In the entire reference manual, the colon syntax is mentioned very briefly, but personally, I find this to be a key syntax to effectively conduct OOP using Lua.