Skip to content

Commit

Permalink
Refactoring: add base_classes.Event class. Relates to lord-server#1558
Browse files Browse the repository at this point in the history
  • Loading branch information
alek13 committed Jul 21, 2024
1 parent b13c94d commit 39bac19
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 0 deletions.
5 changes: 5 additions & 0 deletions mods/lord/Core/base_classes/init.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@


minetest.mod(function(mod)
require("base_classes").init(mod)
end)
5 changes: 5 additions & 0 deletions mods/lord/Core/base_classes/mod.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name = base_classes
title = Base Classes
description = Very handly common base classes to make life easier
depends = builtin
author = alek13
17 changes: 17 additions & 0 deletions mods/lord/Core/base_classes/src/base_classes.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
local Event = require("base_classes.Event")


base_classes = {} -- luacheck: ignore unused global variable base_classes

local function register_api()
_G.base_classes = {
Event = Event
}
end


return {
init = function()
register_api()
end,
}
59 changes: 59 additions & 0 deletions mods/lord/Core/base_classes/src/base_classes/Event.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
local pairs
= pairs


--- @static
--- @class base_classes.Event
local Event = {
Type = {},
subscribers = {},
}

--- @static
--- @return base_classes.Event
function Event:extended(object_or_class)
local class = self
self = object_or_class or {}
return setmetatable(self, { __index = class} )
end


--- @alias base_classes.Event.callback function

--- @param event string name of event (One of `Event.Type::<const>`)
---
--- @return fun(callback:controls.callback)
function Event:on(event)
return function(callback)
self:subscribe(event, callback)
end
end

--- @param event string name of event (One of `Event.Type::<const>`)
--- @param callback controls.callback
function Event:subscribe(event, callback)
assert(self.Type[event], "Unknown controls.Event.Type: " .. event)
assert(type(callback) == "function")

table.insert(self.subscribers[event], callback)
end

--- @private
--- @param event string name of event (One of `Event.Type::<const>`)
--- @vararg any pass args that will be passed to subscribers callbacks. See `controls.callbacks.<func-types>`
function Event:notify(event, ...)
assert(self.Type[event], "Unknown controls.Event.Type: " .. event)

for _, func in pairs(self.subscribers[event]) do
func(...)
end
end

--- @param event string name of event (One of `Event.Type::<const>`)
--- @vararg any pass args that will be passed to subscribers callbacks. See `controls.callbacks.<func-types>`
function Event:trigger(event, ...)
self:notify(event, ...)
end


return Event

0 comments on commit 39bac19

Please sign in to comment.