DRY: don't repeat yourself in Lua

95 Views Asked by At

There is a way to not rewrite the same part (the cycle for i = 1...end) twice?

local function myfunc(frame,method)
    if frame:IsShown() then
        for i = 1, #frame.buttons do
            frame.buttons[i]:HookScript("OnMouseDown", method)
        end
    else
        frame:SetScript(
            "OnShow",
            function(frame)
                for i = 1, #frame.buttons do
                    frame.buttons[i]:HookScript("OnMouseDown", method)
                end
            end
        )
    end
end

Where

  • IsShown(), HookScript() and SetScript() are all in-game API

EDIT

Maybe a recursive function? It seems to work:

local function myfunc(frame,method)
    if frame:IsShown() then
        for i = 1, #frame.buttons do
            frame.buttons[i]:HookScript("OnMouseDown", method)
        end
    else
        frame:SetScript(
            "OnShow", --when "OnShow" is fired, IsShown() become true
            function()
                myfunc(frame,method)
            end
        )
    end
end
0

There are 0 best solutions below