Hash Tables

Whenever you see a bit of code like this:

room->dir_option[dir]->keyword = add_hash (buf2);

This is the game system working hard to save space in RAM by pointing to the same place in memory for variables that are exactly the same. A few good examples of this are:

  • The default room description that's generated when you first create a room. "No Description Set."
  • Room Titles
  • The exits of a room, i.e. North, South, etc...
  • An object description.
  • Object Names
  • Object Descriptions
  • Wounds
  • Wound Locations
  • Lodged items
  • Tracks
  • Clan Names
  • Variable Colors
  • Travel Strings
  • How full a cup is, i.e. half-full, etc...
  • Languages
  • Authors of books or papers
  • Ink Color
  • Handwriting - i.e. 'with precise penmanship'

Let's use the default room description as an example. (If you don't know what the difference is between a pointer and a string variable, please make sure you google it and understand it before you continue.)

We'll start by creating a new room with the rinit command, let's say we perform the command rinit 1001, then goto 1001. We'll see the new room and the description will say 'No Description Set'. Let's create another room with rinit 1002. We goto 1002 and we have the same room description. But our codebase is sneaky; it knows that there are a lot of strings that are duplicated within the gameworld, so instead of using up precious RAM with two identical strings, it just POINTS at the variable in a structure called hash_data, which is a linked list.

To further explain, a room is a structure [troom] of many pieces of data, one of those pieces is the room description. [troom->description], which is a POINTER to the actual string of characters that contain 'No Description Set.' That pointer in the room structure is set by the code when we create the room with a call to add_hash. So when we create the second room (1002), the address that is set in troom->description is the exact same address that is used for the first room (1001). Neat, huh?

The add_hash function looks through the hash table and if it finds a match for 'No Description Set', it simply returns the address of that string variable. If it does not find a match, it will add the variable to the hash table and then return the address of the newly hashed variable.

Copyright 2015 Shadows of Isildur