Skip to content

Commit

Permalink
prevent double execution of on_event.lua
Browse files Browse the repository at this point in the history
makes it safe to dofile("on_event.lua")

(cherry-picked from commit 6010ffe)
  • Loading branch information
V N authored and gfgtdf committed Oct 7, 2018
1 parent 7e4d12e commit 20177db
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions data/lua/on_event.lua
Expand Up @@ -3,19 +3,25 @@ local utils = wesnoth.require "wml-utils"
-- so you have to call this function from a toplevel lua tag or from a preload event.
-- It is also not possible to use this for first_time_only=yes events.

if rawget(_G, "core_on_event") then
return rawget(_G, "core_on_event") -- prevent double execution
end

local event_handlers = {}

local old_on_event = wesnoth.game_events.on_event or function(eventname) end
wesnoth.game_events.on_event = function(eventname)
old_on_event(eventname)
local context = nil
for k,v in pairs(event_handlers[eventname] or {}) do
for _, entry in pairs(event_handlers[eventname] or {}) do
if context == nil then
context = wesnoth.current.event_context
end
v.h(context)
entry.h(context)
end
end


local function on_event(eventname, arg1, arg2)
if string.match(eventname, ",") then
for elem in utils.split(eventname or "") do
Expand All @@ -35,12 +41,13 @@ local function on_event(eventname, arg1, arg2)
event_handlers[eventname] = event_handlers[eventname] or {}
local eh = event_handlers[eventname]
table.insert(eh, { h = handler, p = priority})
-- sort it.
-- prioritize last entry
for i = #eh - 1, 1, -1 do
if eh[i].p < eh[i + 1].p then
eh[i], eh[i + 1] = eh[i + 1], eh[i]
end
end
end

core_on_event = on_event
return on_event

0 comments on commit 20177db

Please sign in to comment.