Approaching OOP in Lua

56 Views Asked by At

this is the first time I try to apply OOP in Lua. This class is a derivative of the "Frame" class already present in the game

LibListView = {}

function LibListView:New(self)
    local listviewmt = {
            buttons  = {}, 
            data = {},
            initiated = true,
        
            OldSetScript = SetScript,
            SetScript = nil,
            -- more parameters and methods
            SetScript = function(self,handler,fnctn)
                local scripts = "OnHide,OnLoad,OnMouseWheel,OnSizeChanged,OnShow,OnUpdate"
                if string.find(scripts,handler) then
                    self:HookScript(handler,fnctn)
                else
                    self.OldSetScript(handler,fnctn)
                end
            end,
        }
        setmetatable(self, { __index = setmetatable(listviewmt, getmetatable(self)) })
        -- not simply setmetatable(main, class) to avoid already present meta overwritting
end

If I write

listview = LibListView:New(self)

the code works fine. At this point, I would like to make sure that the class is created without passing self as a parameter: in short, using the wording

listview = LibListView:New()

to make the code more elegant.

Some advice?

1

There are 1 best solutions below

0
Nifim On

This defines self twice function LibListView:New(self) when you make a method using : instead of . the first param is hidden and named self. What you did here is made the second param also called self.

you have 2 options,

  1. do not put self in the signature just leave it without any params: function LibListView:New(), you will still have access to the param self within the method.

  2. do not use : and define the first param as self: function LibListView.New(self), you can still call this using the : sugar syntax.

Here is a resource for learning more about how : works in lua: Programming in Lua: Chapter 16 – Object-Oriented Programming

This is a particularly relevant quote from the chapter:

This use of a self parameter is a central point in any object-oriented language. Most OO languages have this mechanism partly hidden from the programmer, so that she does not have to declare this parameter (although she still can use the name self or this inside a method). Lua can also hide this parameter, using the colon operator. We can rewrite the previous method definition as

   function Account:withdraw (v)
     self.balance = self.balance - v
   end