Object-Oriented Programming in Lua

 Object-Oriented Programming in Lua


Lua doesn't have built-in support for object-oriented programming, but it can be achieved using tables and metatables. Here's an example:


```lua

local person = {}


function person:new(name, age)

  local obj = {name = name, age = age}

  setmetatable(obj, self)

  self.__index = self

  return obj

end


function person:say_hello()

  print("Hello, my name is " .. self.name .. " and I am " .. self.age .. " years old.")

end


local p = person:new("Alice", 30)

p:say_hello()

In this example, person is a table that serves as a class. The new function creates a new instance of the class and sets its metatable to person. The say_hello function is a method that can be called on instances of the class.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...