Cookbook:Easy Custom Config Variables

From BF2 Technical Information Wiki
Jump to navigation Jump to search

Problem

You are writing a script that has some configuration parameters that you want the server operator to be able to set. So as not to reinvent the wheel, can you make use of one of BF2's existing configuration files?


Solution

Sure! The main BF2 engine won't let you create custom configuration variables, so adding your configuration information to one of the .con files won't work. . . but the default administration module has it's own configuration file (Battlefield 2 Server/admin/default.cfg) that doesn't follow the normal rules; the administration module reads and parses lines in default.cfg, consisting of keyword/value pairs, into a dictionary called options. It doesn't care what keywords/values are listed in default.cfg--even though it only uses three keywords itself ("port", "password", and "allowBatching"), it will load anything it sees into options. This makes it easy to add your own configuration settings, as keyword/value pairs, into default.cfg, and then piggyback on the parser that's built into the administration module to do our dirty work for us.

First, add your configuration variables into the Battlefield 2 Server/admin/default.cfg file, as keyword/value pairs separated by "=" (the parser ignores spaces before and after both the keyword and the value on each line):

clanToKick = EA
areWeHavingFunYet = 1

Then add the following to your script:

 from default import options 

This imports the options dictionary in default (the default administration module) into your script's namespace, so that you can access it without any need to qualify it. Now, any time you want to check the value of one of your custom configuration variables, you can do so by just looking it up in options:

 options['clanToKick'] 

Be sure to note that the administration module parser is pretty basic; all values that it stores in options are strings, so if your parameter has a numeric value, you'll have to coerce it to a numeric type yourself; for example:

 int(options['areWeHavingFunYet']) 


Discussion

It's not entirely true that the parses only stores values into options as strings; it has a hard-coded special case if the variable name happens to be "allowBatching" which will convert several different parameter values into either a boolean True or boolean False. . . but since it's hard-coded, no one else can really make use of that feature.

If you want anything more elaborate than what the administration module parser provides, it's not hard to write your own parser!

One final caveat: this trick only works if your script runs after the administration module has been initialized.


Submitted By

--Woody, inspired by a question from andrewa (at) bigpond-net-au and a suggestion from brandon (at) bf2cc-com.