Search code examples
luaadd-onworld-of-warcraft

How to get 'self' from Lua event handler function?


local tbl = {a = 1}

-- Passed and executed function
function tbl:handleFunc(x, y)
    print(self.a + x + y)
end

-- I know the above code is syntax sugar.
-- tbl["handleFunc"] = function(self, x, y)
--     print(self.a + x + y)
-- end

-- Register event handlers that I can't control the call
Frame:SetScript("OnClick", tbl.handleFunc)

-- Probably called when an event occurs.
tbl.handleFunc(2, 3)

-- Then it will be like this.
tbl.handleFunc(2, 3, nil)

-- So I wrote a function like this
function tbl.handleFunc(x, y)
    local self = tbl  -- This variable is too cumbersome
    -- And this way, every time I call a function, I need to check whether the function definition is a dot (.) Or colon (:)

end

When calling a function, In situations where you can't pass self, Is there a way to use self?

If not, how should I design?


[Solved] I used a translator but I want to be polite. Thank you for the nice answers.


Solution

  • One way to avoid unnecessary work is to write a function that will wrap the function for you before you register it as a handler:

    local tbl = {a = 1}
    
    function tbl:handleFunc(x, y)
        print(self.a + x + y)
    end
    
    function wrap_with(obj, func)
        return function(...)
            return func(obj, ...)
        end
    end
    
    Frame:SetScript("OnClick", wrap_with(tbl, tbl.handleFunc))