Tutorials

March 18, 2009

Using String Variables to Call Functions in AS3

More articles by »
Written by: Par
Tags: , , , , , ,
quicktipimage

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to reddit

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:


Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to reddit


About the Author

Par
Hey! Don't be surprised, I'm a flash developer. While Flash is definitely one of my favorite languages to develop in, most of all I just like making games. If you want to see the games I've developed so far head over to my website, DigitallyBold, in the link below. If you want to know more about what I'm working on now and in the future be sure to follow me on twitter.




17 Comments


  1. 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.


  2. The link didn’t work for me:S

    Here’s it again: http://olve-web.freehostia.com/Platform.swf


  3. dimebagplan

    Its funny because i use this a lot.
    Especially in game programming.


  4. travis

    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?


  5. brian

    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!


  6. grammer man

    trace(“I was ran from a string”);
    should be “I was run”
    past perfect


  7. Par

    lol, grammer man. Thanks but you spelled grammar wrong.


  8. 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.


  9. Mike

    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.


  10. Robert

    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!


  11. 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.


  12. fizzd

    thanks, i actually used this a lot in the previous language i was working with, so finding this was an immense help!


  13. Maggi

    simply awesome thanks for sharing :)


  14. huseyin

    simple and so helpful thanks a lot


  15. Gaian Helmers

    How would you use this to call a parent function?


  16. danbo

    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 !



Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">


Advertisement