Page 1 of 1

Custom variables in plugin

Posted: Sat Nov 22, 2014 9:18 am
by nullable
I want to use custom variables like am_var1 but when I try next code I get an error:

server.cfg

Code: Select all

am_var1 "test_val"


code

Syntax: Select all

from cvars import cvar

def load():
print('%s' % cvar.find_var('am_var1').get_string())


error

Code: Select all

AttributeError: 'NoneType' object has no attribute 'get_string'


How can I get my am_var1 variable?

Posted: Sat Nov 22, 2014 9:43 am
by Ayuto
The reason for the error is that the variable does not exist, so you have to create it in prior to that.

Here is an example:
https://github.com/satoon101/VictimStats/blob/master/addons/source-python/plugins/victim_stats/config.py

And here is the Wiki page which might help you:
http://wiki.sourcepython.com/pages/config

Posted: Sat Nov 22, 2014 10:29 am
by nullable
Please help. What is wrong in my code?

cfg/source-python/hello.cfg

Code: Select all

am_var1 "test_val"


addons/source-python/plugins/hello/info.py

Syntax: Select all

from cvars.public import PublicConVar
# Plugins
from plugins.info import PluginInfo


# =============================================================================
# >> PLUGIN INFO
# =============================================================================
info = PluginInfo()
info.name = 'Hello Plugin'
info.author = 'Team'
info.version = '1.0'
info.basename = 'hello'
info.variable = info.basename + '_version'
info.url = ''
info.convar = PublicConVar(info.variable, info.version, 0, info.name + ' Version')



addons/source-python/plugins/hello/hello.py

Syntax: Select all

from config.manager import ConfigManager

from hello.info import info

def load():
with ConfigManager(info.basename) as config:
var1 = config.cvar('am_var1', 'test_val', 0, 'VAR1')
print('VAR1: %s' % var1)


result

Code: Select all

VAR1: {}

Posted: Sat Nov 22, 2014 9:36 pm
by nullable
What is wrong in my code?

Posted: Sat Nov 22, 2014 9:42 pm
by satoon101
Well, there are 2 things wrong at first glance.

One is an issue with the ConfigManager that we are still working on a fix for. That issue is that when the cfg file is executed, it currently takes 1 tick to get the value if it was changed in the cfg file.

The issue with your code is that you are printing out the config.cvar.CvarManager instance (which is a dictionary). If you want to get the value of the variable, you need to use the convar's get_<type> method:

Syntax: Select all

from config.manager import ConfigManager

from hello.info import info

def load():
with ConfigManager(info.basename) as config:
var1 = config.cvar('am_var1', 'test_val', 0, 'VAR1')
print('VAR1: %s' % var1.get_string())


Again, though, currently that will always be the original value you set it to (test_val) on first load. We will work to fix this so that that isn't the case.

Posted: Sat Nov 22, 2014 9:52 pm
by nullable
Thanks. The problem has been resolved.