Lua - Functions within Table



A table is a versatile data structure in Lua. We can define functions within a table in order to implement object oriented programming in Lua. Such functions are referred as methods which are to operate on the table itself. table is referred using self keyword.

Defining a method for a table

We can define a method within a table in multiple ways. Following example uses dot (.) notation.

main.lua

-- define a table 
Rectangle = {
   length = 10, breadth = 5
}

-- define a method
Rectangle.area = function (self)
   return self.length * self.breadth
end

-- create rectangle object
r1 = Rectangle

-- compute and print area of Rectangle object
print(r1.area(r1))

Output

When the above code is built and executed, it produces the following result −

50

Following example shows declaration of method within table.

main.lua

-- define a table 
Rectangle = {
   length = 10, breadth = 5,
   
   -- define a method
   area = function (self)
      return self.length * self.breadth
   end   
}

-- create rectangle object
r1 = Rectangle

-- compute and print area of Rectangle object
print(r1.area(r1))

Output

When the above code is built and executed, it produces the following result −

50

Define a function using colon(:)

As we've seen that to refer to table, we've used self keyword. Using colon, we can define the method without need to use self as argument. This is also termed as syntactic sugar code.

main.lua

-- define a table 
Rectangle = {
   length = 10, breadth = 5
}

-- define a method
function Rectangle:area()
   return self.length * self.breadth
end

-- create rectangle object
r1 = Rectangle

-- compute and print area of Rectangle object
print(r1:area())

Output

When the above code is built and executed, it produces the following result −

50
Advertisements