• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • It's time for the first HD Modeling Contest of 2024. Join the theme discussion for Hive's HD Modeling Contest #6! Click here to post your idea!

[Lua] [Deprecated] AnyPlayerUnitEvent (GUI-friendly)

Bribe

Code Moderator
Level 50
Joined
Sep 26, 2009
Messages
9,468
The below script is a combination of a script that I wrote ~10 years ago, but now with combining it with Lua function overriding.

Further details about the background of such systems can be found here: [Snippet] RegisterEvent pack. Mainly, it was created to help to cut down on handles that are generated for events, but this has the benefit of using raw function calls + potentially benefiting from Lua Fast Triggers.

API is rather simple:

  • GUI Trig
    • Events
      • Unit - A unit Dies
    • Conditions
    • Actions
      • -------- This is already benefiting from this Lua resource --------
Lua:
local function myFunc() print "a unit has died" end
AnyPlayerUnitEvent.add(EVENT_PLAYER_UNIT_DEATH, myFunc)
--
-- some time later (if wished)...
--
AnyPlayerUnitEvent.remove(EVENT_PLAYER_UNIT_DEATH, myFunc)

On with the code:

Lua:
do --AnyPlayerUnitEvent v1.0 by Bribe

AnyPlayerUnitEvent = {}

local fStack = {}
local tStack = {}
local bj = TriggerRegisterAnyUnitEventBJ

function AnyPlayerUnitEvent.add(event, userFunc)
    local r, funcs = 0, fStack[event]
    if funcs then
        r = #funcs
        if r == 0 then EnableTrigger(tStack[event]) end
    else
        funcs = {}
        fStack[event] = funcs
        local t = CreateTrigger()
        tStack[event] = t
        bj(t, event)
        TriggerAddCondition(t, Filter(
        function()
            for _, func in ipairs(funcs) do func() end
        end))
    end
    funcs[r + 1] = userFunc
    return userFunc
end

function AnyPlayerUnitEvent.remove(event, userFunc)
    local r, funcs = -1, fStack[event]
    if funcs then
        for i, func in ipairs(funcs) do
            if func == userFunc then r = i break end
        end
        if r > 0 then
            r = #funcs
            if r > 1 then
                funcs[i] = funcs[r]
            else
                DisableTrigger(tStack[event])
            end
            funcs[r] = nil
            r = r - 1
        end
    end
    return r
end

function TriggerRegisterAnyUnitEventBJ(trig, event)
    return RegisterAnyPlayerUnitEvent(event,
    function()
        if IsTriggerEnabled(trig) then
            ConditionalTriggerExecute(trig)
        end
    end)
end

end
 
Last edited:
Top