Strange bug with Dictionary

A strange bug I found today:

Attempting to set a Dictionary item with key nil will then cause the Dictionary to behave erratically, without raising the slightest exception.

The code below creates a Dictionary which is mysteriously missing keys 2, 4, 7, 9, 10, 11.

(
a = Dictionary.new;

a[nil] = 0;

12.do{|i|
	if(a[i] == nil,{
		a[i] = "yes";
	});
};
a.keysValuesDo{|key, val|
	[key,val].postln;
};
)

The code below creates the Dictionary normally, with all keys 0 - 11:

(
a = Dictionary.new;

// a[nil] = 0;

12.do{|i|
	if(a[i] == nil,{
		a[i] = "yes";
	});
};
a.keysValuesDo{|key, val|
	[key,val].postln;
};
)

At the very least, if setting the nil key of a Dictionary causes unpredictable problems, SC should raise an error. This was quite a puzzle to figure out today.

agreed that SC should throw an error here.

it seems to come up from time to time, this question of what is nil? it’s meant to express the idea of a non-value, the absence of a value. using it as a dictionary key is treating this non-value as the presence of a concrete absence-of-value – a self-contradiction. that’s a long way of saying, don’t do that :wink: if you need a neutral key, maybe a symbol \nil would be better than a real nil.

hjh

Thanks @jamshark70. To be clear, I didn’t set this intentionally! This was part of a much more complicated block of code and it took me a while to realize that the key could be nil at times. The code above is just for demonstration. The point here is that SC should throw an error, it would help debug this kind of situation much more efficiently.

Ah ok – sorry for presuming.

I’ve just gone and done:

hjh

Amazing, @jamshark70! Thanks much for this. Will save some of us some headaches in the future.