Is there a way to initialise and declare a Dictionary in a single line like this in Unity’s javascript, or do you have to use many lines of letterScore.Add(“A”, 5); to fill it out?
I can get it working with a Hashtable easily enough, but could not find a syntax that works for Dictionary in Unity’s javascript.
Or, is there a better way to do something simple like this than using Dictionary?
As an indexed array, I have to do a lot of casting and converting between unicode character values to array index values which is how I did it initially, and exactly the thing I am trying to avoid by using a dictionary.
I have a bunch of single letter strings, the intended usage is along the lines of :
var wordScore:int = letterScore["W"] + letterScore["O"] + letterScore["R"] + letterScore["D"];
// or more precisely...
for (var tile: Tile in buffer){
wordScore += letterScore[tile.letter]; // tile.letter is a string
}
Eric, yup, I get it. As I said, that is very close to the way I had it originally, except that “tile.letter[0] - 65” actually throws an error in Unityscript (operator ‘-’ cannot be used with left hand char and right hand int), so it’s spread out across a couple of lines with a temp var, casting from string > char > int. Also because the score calculator is doing the entire board full of tiles at once (up to about 200 words) I was doing the casting and - 65 once on init of the tile rather than in the inner loop of the score calculator, and storing the int alongside the string in the tile. This seems like cruft to me, especially when it means I need custom setters to keep the int and string in sync. This is why I was looking at using a dictionary instead of an array, but could not find a working initializer syntax.
So, should I assume there simply is no collection initializer syntax for Dictionaries in Unityscript? (the link frosted posted was in C# BTW)
var charValue : int = tile.letter[0];
wordScore += letterScore[charValue - 65];
I don’t know about the initializer syntax for Dictionaries but personally I’d probably just use an array, since the conversion is so trivial, and it would perform better. You could make things a little simpler with a property; say this is your Tile class:
class Tile {
var letter : String;
function get LetterIndexValue () : int {
var charValue : int = letter[0];
return charValue - 65;
}
}
Then your score code would be:
for (var tile in buffer) {
wordScore += letterScore[tile.LetterIndexValue];
}
If speed is important, looking up a value in an int[ ] array is much faster than using strings as keys in a Dictionary, even with the char → int conversion.