helper_constructors.lua

main 53 lines · 1.3 KB Raw
Alex Alex Commit Server upload 18/10/2026 23:38
1local classes = {Action, CreatureEvent, Spell, TalkAction, MoveEvent, GlobalEvent, Weapon}
2
3for _, class in ipairs(classes) do
4 local MT = getmetatable(class)
5 local DefaultConstructor = MT.__call
6
7 MT.__call = function(self, def, ...)
8 -- Backwards compatibility for default obj() constructor
9 if type(def) ~= "table" then
10 return DefaultConstructor(self, def, ...)
11 end
12
13 local obj = nil
14 if def.init then
15 obj = DefaultConstructor(self, unpack(def.init))
16 else
17 obj = DefaultConstructor(self)
18 end
19
20 -- Call each method from definition table with the value as params
21 local hasCallback = false
22
23 for methodName, value in pairs(def) do
24 -- Strictly check if a correct callback is passed
25 if methodName:sub(1, 2) == "on" and type(value) == "function" and rawget(class, methodName) then
26 hasCallback = true
27 end
28
29 if methodName ~= "register" then
30 local method = rawget(self, methodName)
31 if method then
32 if type(value) == "table" then
33 method(obj, unpack(value))
34 else
35 method(obj, value)
36 end
37 end
38 end
39 end
40
41 -- Only register if callback has already been defined, otherwise defining afterwards will not work
42 if def.register then
43 if not hasCallback then
44 print("Warning: Event not registered due to there being no callback.")
45 else
46 obj:register()
47 end
48 end
49
50 return obj
51 end
52end
53
Top