oop: how to instantiate objects from a class using constructor in lua

Lua is not an Object-Oriented Programming Language but it provides all the facilities to let this to be accomplished.
In particular Lua uses some special functions which are called metamethods that allow the user to execute some behavior that are similar to other programming languages that supports OOP from their own.

With that being said, below i've added a simple table that contains some properties reffered:

local motherBoard = {speed = "0.5", material = "iron", support = "32bit"}

All these properties are stricly representative to the table's name "motherBoard".
Here this table is just a normal table like others, so this table to become a class needs a constructor.
The constructor is a simple function that do special things such as settings a table when this function is called, then sets this table as a metatable with the class, sets an index metamethod so every object it can instantiate would have the same properties of the class and then it returns the object.

Let see how it works:

Lua = function(self, object)
    object = object or {}
    setmetatable(object, self)
    self.__index = self
    return object

Here the constructor function was simple declared and structured.
As the first argument of the function it takes the "self" argument and this is done because, instead of accessing the function with a dot sign, you can do it by using the colon sign.

Let see how to create a new object from this class:

Nvidia = motherBoard:new()

One thing that you have to know is that until you don't call its properties, the "Nvidia" tables will have no properties.
And this is where it comes into action the index metamethod which takes as reference the "motherBoard" class and take from it the existing properties that are needed.

print(Nvidia.speed)     -- will print 0.5
print(Nvidia.material)  -- will print iron
print(   -- will print 32bit

When you print its properties Lua sees that at first Nvidia table has no fields with this name but it also sees that Nvidia has a metatable with an index metamethod which passed the value to the missing key you are providing.

Additional behaviors

Also you can pass to the constuctor a table as well which can define a specific table from others:

AMD = motherBoard:new({speed = "0.1", support = "x86_64"})

Doing this way you are defining the same properties but with different values.
NOTE: Now the AMD table has 2 visible fields: speed and support.
When you print this values Lua don't need to go inside the motherBoard table and instantiate the value to the provided key, it only goes inside the AMD table and then take the existing field!

print(AMD.speed)     -- will print 0.1
print(AMD.material)  -- will print iron
print(   -- will print x86_64

Do you want to see a video related on Metatables?

programming language lua oop
Expand your knowledge about this topic