Skip to content

Commit 759953f

Browse files
committed
Added ConVarChanged decorator class to cvars.
1 parent ea5fab5 commit 759953f

File tree

1 file changed

+61
-0
lines changed
  • addons/source-python/packages/source-python/cvars

1 file changed

+61
-0
lines changed

addons/source-python/packages/source-python/cvars/__init__.py

100644100755
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
# >> IMPORTS
77
# =============================================================================
88
# Source.Python Imports
9+
# Core
10+
from core import AutoUnload
911
# Cvars
1012
from _cvars import ConVar
1113
from _cvars import _Cvar
@@ -24,5 +26,64 @@
2426
# >> ALL DECLARATION
2527
# =============================================================================
2628
__all__ = ('ConVar',
29+
'ConVarChanged',
2730
'cvar',
2831
)
32+
33+
34+
# =============================================================================
35+
# >> CLASSES
36+
# =============================================================================
37+
class ConVarChanged(AutoUnload):
38+
"""ConVarChanged decorator class."""
39+
40+
def __init__(self, *convars):
41+
"""Store the convars."""
42+
self._convars = ()
43+
self.callback = None
44+
45+
# Validate convars
46+
if not convars:
47+
raise ValueError('At least one convar is required.')
48+
49+
_convars = []
50+
for convar in convars:
51+
if not isinstance(convar, (str, ConVar)):
52+
raise ValueError('Given convar is not ConVar or ConVar name.')
53+
54+
elif isinstance(convar, str):
55+
convar_name = convar
56+
convar = cvar.find_var(convar_name)
57+
if convar is None:
58+
raise ValueError(
59+
f'"{convar_name}" is not a valid ConVar name.')
60+
61+
_convars.append(convar)
62+
63+
self._convars = tuple(_convars)
64+
65+
def __call__(self, callback):
66+
"""Store the callback and add it to convars."""
67+
# Store the callback
68+
self.callback = callback
69+
70+
# Loop through all convars
71+
for convar in self._convars:
72+
73+
# Add the callback
74+
convar.add_changed_callback(self.callback)
75+
76+
# Return the callback
77+
return self.callback
78+
79+
def _unload_instance(self):
80+
"""Remove the callback from convars."""
81+
# Was no callback registered?
82+
if self.callback is None:
83+
return
84+
85+
# Loop through all convars
86+
for convar in self._convars:
87+
88+
# Remove the callback
89+
convar.remove_changed_callback(self.callback)

0 commit comments

Comments
 (0)