Skip to content

Added the ability to add callbacks to ConVar that will be called when ConVar is changed. #421

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Prev Previous commit
Next Next commit
Added ConVarChanged decorator class to cvars.
  • Loading branch information
CookStar committed Oct 2, 2021
commit 759953f727fac97261e0c9822b2c36fa14a81ea4
61 changes: 61 additions & 0 deletions addons/source-python/packages/source-python/cvars/__init__.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
# >> IMPORTS
# =============================================================================
# Source.Python Imports
# Core
from core import AutoUnload
# Cvars
from _cvars import ConVar
from _cvars import _Cvar
Expand All @@ -24,5 +26,64 @@
# >> ALL DECLARATION
# =============================================================================
__all__ = ('ConVar',
'ConVarChanged',
'cvar',
)


# =============================================================================
# >> CLASSES
# =============================================================================
class ConVarChanged(AutoUnload):
"""ConVarChanged decorator class."""

def __init__(self, *convars):
"""Store the convars."""
self._convars = ()
self.callback = None

# Validate convars
if not convars:
raise ValueError('At least one convar is required.')

_convars = []
for convar in convars:
if not isinstance(convar, (str, ConVar)):
raise ValueError('Given convar is not ConVar or ConVar name.')

elif isinstance(convar, str):
convar_name = convar
convar = cvar.find_var(convar_name)
if convar is None:
raise ValueError(
f'"{convar_name}" is not a valid ConVar name.')

_convars.append(convar)

self._convars = tuple(_convars)

def __call__(self, callback):
"""Store the callback and add it to convars."""
# Store the callback
self.callback = callback

# Loop through all convars
for convar in self._convars:

# Add the callback
convar.add_changed_callback(self.callback)

# Return the callback
return self.callback

def _unload_instance(self):
"""Remove the callback from convars."""
# Was no callback registered?
if self.callback is None:
return

# Loop through all convars
for convar in self._convars:

# Remove the callback
convar.remove_changed_callback(self.callback)