Add/Set a hashtable value easily
16th March, 2011
Scripting
When you want to set a key/value in a hashtable, you have to check if the key is already existing before doing a hashtable.set (), because if the key doesn’t exists, the function won’t do anything.
The solution
To solve this problem without making your script unreadable, I suggest you to create a function “addToHashtable” you will call, which will do automatically the check and add the key and in the hashtable if not existing, or only set the value in the other case.
The function take 3 parameters: the hashtable, the key and the value.
The code of the function is this one:
-------------------------------------------------------------------------------- function MyGame.addToHashtable ( htHashtable, sKey, vValue ) -------------------------------------------------------------------------------- if ( hashtable.contains ( htHashtable, sKey ) ) then -- If the key is in the hashtable, update the value hashtable.set ( htHashtable, sKey, vValue ) else -- If the key is not in the hashtable, create a new entry in the hashtable, with sKey and vValue as key/value for this entry. hashtable.add ( htHashtable, sKey, vValue ) end -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
You can call the function like that:
this.addToHashtable ( this.myHashtable ( ), “myKey”, 3 )
Leave a Reply



(3 votes, average: 4.00 out of 5)



