Tuesday, February 8, 2011

Conundrum

While working on a given assignment in my Flash/actionscript course, I came across a neat problem. I've got a function that creates a given type of object (a tile, in fact), depending on what sort of variable I call the function with. This feels sort of difficult to explain, so let me go straight to my example:

function addblock(type:int){
switch(type) {
case 1: var newblock = new mc_asphalt(); break;
case 2:var newblock = new mc_dirt(); break;
default: var newblock = new mc_asphalt();
}
addchild(newblock);

As you see, I either create a block consisting of the movie clip mc_asphalt, or of mc_dirt (the real version has even more types, but that's irrelevant right now). Anyways. This compiles and runs, but I get some errors. Because I declare the variable in a switch, the compiler reads it as me trying to declare the same variable several times in sequence. The error message is "Duplicate variable definition".
The easiest way around this would surely be to spread it out to different functions, one for each type of block, but that'll involve a lot of copying and pasting, and redundant code. So, where does this leave me?

1 comment:

Thomas B said...

..and if anyone would ever be interested in this sort of problem, the answer is called Factory Method Pattern (http://en.wikipedia.org/wiki/Factory_method_pattern)