Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

A noobs questions to Variant and the "right way" to do things.

Moderators: larsivi kris

Posted: 09/06/08 18:03:37

Hi

I am writing a simple module to store my games settings in a map and have some basic D/Tango questions. 1. I was wondering what the recomended way is to overload opEquals, opCmp, and toHash. Is it even needed in my case? 2. Will the way im comparing Variant to null result in problems when I store atomic types and objects? 3. What type of ma should I use to store my settings? atm im using a treemap with the setting name as a key.

module util.Config;

import tango.core.Variant;
import tango.util.collection.TreeMap;

class Setting
{
	this(char[] name, Variant value, Variant defaultValue)
	{
		this.name = name;
		this.value = value;
		this.defaultValue = defaultValue;
	}

	char[] getName()
	{
		return name;
	}

	Variant getValue()
	{
		// TODO problem with null cmp Variant?
		if(value == null || value.isEmpty)
		{
			return defaultValue;
		}
		return value;
	}
	
	void setValue(Variant value)
	{
		this.value = value;
	}
	
	Variant getDefault()
	{
		return defaultValue;
	}

	bool opEquals(Setting other)
	{
		return	this.name == other.name &&
				this.value == other.value &&
				this.defaultValue == other.defaultValue;
	}

	int opCmp(Setting other)
	{
		if(this == other) return 0;
		if(this.name > other.name) return 1;
		return -1;
	}

	private
	{
		char[] name;
		Variant value;
		Variant defaultValue;
	}

	invariant()
	{
		// setting must have a name
		assert(name != "");

		// default value must be set
		assert(defaultValue != null);  
		assert(defaultValue.isEmpty == false);

		// value and default value must be of the same type
		if(value != null)
			assert(value.type == defaultValue.type);
	}
}
Author Message

Posted: 09/07/08 08:59:13

  1. assert(defaultValue != null); Variant is a struct, not a class, so it always exists, and this operation asks "is the Variant's value null?", and so may not even be a valid question to ask. For class objects, you should use "is null" not "== null" anyway, but for structs you don't need to check this.
  2. Hashmaps are faster than treemaps (although they take more memory).

A few other points:

Posted: 09/07/08 13:58:33

Maybe you should try DWin which contain dwin.sys.win32.com.Client module, where you can find all what you need.

Posted: 09/07/08 15:48:46

*throws away code and checks out mde*
I have thought the same about the map but the default is important to me and want to save and load the cfg.
Guess I havnt thought about forcing the type check ;>
Sorry Uwar I run linux and would like me game to be multiplatsorm.
However I would still like to know what the porpper way to implement opEquals, opCmp, toHash and when I need to do this.
thx for help btw