Static vs Dynamic

September 28, 2009

Since I’m now officially a wizard (Immortal/coder) on SWMud, I figured I’d share some LPC knowledge. I’m constantly improving and optimizing my own code based on looking at code belonging to so called ‘experts’. Along the way, I’ve learned a few things.

For this entry, we’re simply going to compare two types of coding. And in this particular case, I only have one really good example. I’m sure you could think up hundreds more once you put your mind to it.

Below is an example of code I see all the time:

   1: switch(random(2)){ 

   2: case 0: write(“Random thing 1.”); 

   3: break; 

   4: case 1: write(“Random thing 2.”); 

   5: break; 

   6: case 2: write(“Random thing 3.”); 

   7: break; 

   8: default: write(“Random broke.”); 

   9: }

First things first, remember that random() ranges from 0 (zero) to the integer you specify. People often forget this and don’t include a case for 0 in their switch statements.

The above code is not very dynamic. It’s written easily, with beginner skills (not to say that some experts wouldn’t use it, it has its uses). The trick to this code is that every time you want to add a new random thing, you have to edit your switch statement to increase random(), AND add another case. This code is static. It’s not meant to be easily updated, it’s meant to do its job.

What about this code?

   1: string *things;

   2: things = ({ "Random Thing 1.", "Random Thing 2.", "Random Thing 3." }) ;

   3: write(things[random(sizeof(things))]);

This code is much more dynamic. We’re providing the exact same end result, but now the code is smart enough to know how many items it has to iterate through randomly, without having you add more cases to a switch statement.

We define things as an array of strings. An array is just a collection of stuff, remember. Then we set ‘things’ to be a collection of three strings, the same strings we would’ve used previously. Finally, we write a random member of the things array to the user. sizeof() is used to get the absolute size of an array, so that number will always be the exact number of members in your array, no matter how many things you add to it. You should already know that you can refer to members of an array by their index in that array, so things[0] would return the first member of things. This works to our advantage here, where we pull that number using random() and sizeof() combined. So randomly, things[0], things[1], or things[2] will be written to the user.

Pretty nifty, eh?