-
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?
-
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.
-
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)?
-
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
-
Originally Posted by 5TonsOfFlax
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|