Home Tutorials Download Store Forum Documentation Wiki Blog
Add/Set a hashtable value easily

Scripting

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 4.00 out of 5)
Loading ... Loading ...

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 )

Tags: , ,

Leave a Reply

Leave a Reply

You must be logged in to post a comment.