Have you ever wanted to use a string to call a function? What do you mean, you ask? Well let me explain. Let’s say I have a variable called myfunc that is a string with “functionFromVariable” stored in it. Here’s the code:
var myfunc:String = "functionFromVariable";
Nothing too complex huh? Now let’s also say I have a function called functionFromVariable. Here’s its code:
public function functionFromVariable() : void { trace("I was ran from a string"); }
Alright. So now I want to call our functionFromVariable function using our string. From inside our class all I have to do is:
this[myfunc]();
That’s great I know… now why would you ever want to do that? I know, it’s probably rare at best but I’ll give you too crazy off beat examples that could make sense.
Example 1: Calling Functions in a Series
I’ve used this setup before to do exactly what I am about to show you. I wrote a tutorial class once that had a series of functions called: step1, step2, step3, step4, step5 … and so on. Now I didn’t want to keep track of what step I was on as I traveled through the list. See when a step was completed it called a stepCompleted function that went to the next step. Since stepCompleted was used at the end of each step I could not just blatantly call the next step. The solution was simple though, I just needed to attach a number onto step each time.
So what did I do? I created a variable called currentStep that was an int and incremented it at the beginning of stepCompleted each time. Then I could simply call this["step"+currentStep](); to run the next step. So my stepCompleted function looked like this:
public function stepCompleted() : void { currentStep++; // my class variable to track the current step this["step"+currentStep](); //call the next function in the series }
Worked like a charm and called functions step1, step2, step3, and so on until I told it otherwise at the end of the tutorial.
Example 2: Randomly calling Functions to set Enemy Attack Patterns
Let’s say you have an enemy that has four modes of movement: jump, walk, fly, swim. And two different attack modes: defensive, offensive.
Well logically you’d probably control these two things separate from each other. But in our case we want our enemy to act completely different if defensive jump mode than in defensive fly mode. And really, I just want to show you it works, even if this is the stupidest example ever.
So here’s what we can do.
Make two arrays:
var movement:Array = ["jump", "walk", "fly", "swim"]; var attack:Array = ["defensive", "offensive"];
Now let’s say we create a different function for every combination. That’s eight functions, Here’s a list as an example:
- jumpdefensive
- jumpoffensive
- walkdefensive
- walkoffensive
- flydefensive
- flyoffensive
- swimdefensive
- swimoffensive
So you’ve got these 8 different functions and you want to randomly call one every so often to change to characters mode. All you have to do is randomly select an item from each array and call it with () on the end. Like this:
this[movement[Math.floor(Math.random()*movement.length)]+attack[Math.floor(Math.random()*attack.length)]]();
Yeah that was probably too long and confusing to read. Don’t freak out, here’s a cleaner example:
this[movement[2]+attack[1]]();
So in the directly above case we would be calling this.flyoffensive();
Closing
So that’s pretty much it. I’m sure there are more reasons for using this method, but now that you know how to do it, you’ll be ready to use it when they arise.
Similar Posts:
- Making a Complete Flash Game: Menus, UI, Screens, or Windows
- AS3 Flash Games for Beginners: Scores, HUDS, and User Interface
- An Even Better AS3 OOP Flash Custom Cursor
- Changing Colors Dynamically with ColorTransform in AS3
- AS3 Character Movement: Asteroids Style 360 Degree Movement









I have made my first game, mostly based on your tutorials: http://olve-web.freehostia.com/Platform.swf
It’s a simple game, where you play a red ball bouncing around, avoiding enemies and collecting coins. You steer with the arrow keys and you can move in all four directions. The game has gravity, which the character cannot escape, so you have to bounce. The enemies come falling down, and you loose a life if you get hit. After loosing three lifes, it’s game over and you loose control over the character. You cannot be hit by any more enemies or coins.
The enemies, three sorts, all share a basic AI making them move towards your character. The green one is fast but inaccurate. The blue t-ball is slower and more accurate, but rarer. The watchmen-inspired smiley-ball is even faster, has more friction and has the ability to bounce. When it stops moving, it will drop below the screen. When it does, it will, like the other enemies, be removed.
The coins spawn randomly on the stage, and you get points for collecting them. The more coins you have, the more rapid enemies will spawn.
Please tell me what you think;) I can also send you the source code, if you’re interested.
I think the game needs a preloader and a menu, I’m hoping that will get covered in your next tutorials.
The link didn’t work for me:S
Here’s it again: http://olve-web.freehostia.com/Platform.swf
Here I have embedded it: http://olve-web.freehostia.com/bouncyball.html
Its funny because i use this a lot.
Especially in game programming.
Hey man this is good stuff. I was wondering how I could apply this to my characters in my rpg. Currently, my hero can walk and jump, but these are all different animations that have been labeled inside the hero.mc. I’m looking to add the abilities to fight and pick up weapons and dash.
Do you have any example code for this and how the user interacts w/ the keyboard?
this is great! i’m working with AS2. i tried it and it doesn’t work. do you kno how to do the same thing in actionscript 2. Thanks!
trace(“I was ran from a string”);
should be “I was run”
past perfect
lol, grammer man. Thanks but you spelled grammar wrong.
This is great info. I am enjoying all of your tutorials. This one is especially useful, since it can be linked to the responses of an AI.
any tips on how to modify this to call a function on the stage from an object’s script, for example:
var callThis:String = “functionName”;
var _r:Object = MovieClip(root);
function callFunction(e:MouseEvent):void{
_r.[callThis]();
}
This returns a syntax error -
1084: Syntax error: expecting identifier before leftbracket.
YOU RULE!!! This tutorial has helped me tremendously! As they all have! Are there any tutorials on base classes? Other than menu UI? Thanks again, ASGAMER RULES!
Thank you very much for this tutorial. Helped me a lot. It can be used in many different functions, as I did in my site.
thanks, i actually used this a lot in the previous language i was working with, so finding this was an immense help!
simply awesome thanks for sharing
simple and so helpful thanks a lot
How would you use this to call a parent function?
As always, little things make great effects.
Generally we think bad ’cause we are looking for complex things.
It’s clever, thanks much.
Here is what I call …good programming !