A Flash Developer Resource Site

Results 1 to 5 of 5

Thread: store functions in an array?

  1. #1
    Member
    Join Date
    Mar 2009
    Posts
    62

    store functions in an array?

    is it possible? I want to generate a random number and use that number to run whatever function appears at that index in the array. Is it possible?

  2. #2
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    Yes, that's no problem. In AS3, functions are first-class objects of type Function, so you can do anything with them you can with other objects, including store references to them and pass them around.

  3. #3
    Member
    Join Date
    Mar 2009
    Posts
    62
    Thats great. I'm sure I tried it before and it didn't work though. Can I manually add them to the array eg myArray:Array = new Array(function1(),function2()...)
    or do it do it by way of array.push(function1)?

  4. #4
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    The reason the first way doesn't work is because by adding () after the function, you are invoking the function. So you're actually putting the result of calling that function into the array. If that function returns void, then nothing goes in.

    Code:
    var myArray:Array = [function1, function2, function3];
    myArray.push(function4);
    
    //later
    myArray[0](); //invoke function1

  5. #5
    Member
    Join Date
    Mar 2009
    Posts
    62
    Quote Originally Posted by 5TonsOfFlax View Post
    The reason the first way doesn't work is because by adding () after the function, you are invoking the function. So you're actually putting the result of calling that function into the array. If that function returns void, then nothing goes in.

    Code:
    var myArray:Array = [function1, function2, function3];
    myArray.push(function4);
    
    //later
    myArray[0](); //invoke function1
    Thank you. That makes life a whole lot easier

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center