diff --git a/mods/lord/Core/base_classes/init.lua b/mods/lord/Core/base_classes/init.lua new file mode 100644 index 000000000..0b5481b9a --- /dev/null +++ b/mods/lord/Core/base_classes/init.lua @@ -0,0 +1,5 @@ + + +minetest.mod(function(mod) + require("base_classes").init(mod) +end) diff --git a/mods/lord/Core/base_classes/mod.conf b/mods/lord/Core/base_classes/mod.conf new file mode 100644 index 000000000..ca891f066 --- /dev/null +++ b/mods/lord/Core/base_classes/mod.conf @@ -0,0 +1,5 @@ +name = base_classes +title = Base Classes +description = Very handly common base classes to make life easier +depends = builtin +author = alek13 diff --git a/mods/lord/Core/base_classes/src/base_classes.lua b/mods/lord/Core/base_classes/src/base_classes.lua new file mode 100644 index 000000000..92657d9ce --- /dev/null +++ b/mods/lord/Core/base_classes/src/base_classes.lua @@ -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, +} diff --git a/mods/lord/Core/base_classes/src/base_classes/Event.lua b/mods/lord/Core/base_classes/src/base_classes/Event.lua new file mode 100644 index 000000000..0f2a73277 --- /dev/null +++ b/mods/lord/Core/base_classes/src/base_classes/Event.lua @@ -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::`) +--- +--- @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::`) +--- @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::`) +--- @vararg any pass args that will be passed to subscribers callbacks. See `controls.callbacks.` +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::`) +--- @vararg any pass args that will be passed to subscribers callbacks. See `controls.callbacks.` +function Event:trigger(event, ...) + self:notify(event, ...) +end + + +return Event