Syntax: Select all
# ../addons/source-python/packages/source-python/refcount.py
# =============================================================================
# >> IMPORTS
# =============================================================================
# maybe import and do some logging like in the other libs..
# Source.Python
# Cvars
from cvars import ConVar
# =============================================================================
# >> CLASSES
# =============================================================================
class _Variables(dict):
"""Class used to provide refcount functionality for server variables."""
def __init__(self):
"""Call dict's __init__() method."""
super(_Variables, self).__init__()
def __missing__(self, variable):
"""Adds the variable to this dict, if it doesn't exist yet."""
# Set the variable's count to 0
self[variable] = 0
def increment(self, variable, desired_value=1):
"""Increments the variable's refcount and sets
the variable's value to the desired one, if it isn't already set."""
# get a ConVar instance of the variable
cvar = ConVar(variable)
# increment the refcount for the variable
self[variable] += 1
# set it's value to the desired one, if it isn't already set
if cvar.get_int() != desired_value:
cvar.set_int(desired_value)
# TODO: add support for other variable types
def decrement(self, variable):
"""Decrements the variable's refcount and sets
the variable's value to its default, if it isn't already set."""
# get a ConVar instance of the variable
cvar = ConVar(variable)
# decrement the refcount for the variable
self[variable] -= 1
# is it time to set the variable's value back to default?
if self[variable] <= 0:
# if yes, set the variable's value back to default
# if it isn't already set
if cvar.get_int():
cvar.revert()
# remove the variable from this dict as it is not needed anymore
del self[variable]
# Instantiate the _Variables class
variables = _Variables()