Lua function selector - function

I have 3 functions. When the user presses the 'E' key I want it to select one of the functions (at random), I feel like it has something to do with math.random but I can't figure it out.

You don't use math.random to select a function; you use it to pick a random number, which you can then use as an index to get the function you need from a table (as one example):
local list = { function() print(1) end, function() print(2) end, function() print(3) end }
math.randomseed(os.time()) -- don't forget to seed or you likely to get the same sequence
for i = 1, 10 do list[math.random(#list)]() end

Related

How to randomly choose a function?

how can I use a variable in your code? I am thinking of writing:
example:
I have a variable x = Math.random (4);
I have a function: timedFunctionb1, timedFunctionb2, timedFunctionb3, timedFunctionb4
Now I want to add X to the function name:
timedFunctionb .....
as there add the variable name to use it when setTimeout (timedFunctionb.x, 5000); it does not work like that. I can not find the correct definition.
Put all functions in an array
var functions:Array = [timedFunctionb1, timedFunctionb2, timedFunctionb3, timedFunctionb4];
Then pick a random element:
setTimeout (functions[Math.floor(Math.random() * functions.length)], 5000);

How does "Passing in Parameters" work?

With about every language that I learn more about, I always hear about, "passing in parameters".
Could you explain it like, "for a dummy" style? :)
An example of what I am talking about below..
function myfunction(para1, para2) {
//run code here...
}
So, where does para1, and para2 come from?
Why do they exist?
What is their use?
Etc..
I have looked around trying to figure out what they're and where they come from, but something isn't clicking.
Before I answer your question, I think you should know what a function (or a method) is in the first place.
A function is a block of code where it will only execute when you call(invoke) it, otherwise it just sit there doing nothing. There are tonnes of benefits using functions:
Modularization of codes
Makes your codes easier to read and debug
Ease the maintenance of your codes
Implement once, use n times
and more..
Now, imagine you have a function call getMax(). It is a very general function where you it will return you the larger value when you give (pass) values to it.
Since it shall receive 2 values for its calculation, the function will accept 2 arguments (mentioned as parameter in your question).
So now getMax() shall look like getMax(int val1, int val2).
So with the 2 given values:
if val1 > val2, then
return val1
else return val2
From here we see that the 2 args (arguments) can be any 2 integer values provided by you.
You can also imagine a function as a machine. For example, having an ice-cream making machine. You need to provide the ingredients (such as cream and milk) for ice-cream making.
In this case, the ice-cream machine is your function, the arguments in the parameter list are the ingredients needed (cream, milk), and the return value is the ice-cream:
function IceCream iceCreamMaker(Cream cream, Milk milk){
return iceCream;
}
To complement #user3437460's answer:
So if you have function getMax(int val1, int val2), which looks like:
function getMax(val1, val2) {
if (val1 > val2) {
return val1;
} else {
return val2;
}
}
Then you want to invoke/call it, for example, when a user clicks on a button.
Now, when you call it, instead of using "getMax()", you'll put your two variables in the parenthesis, in the same order as the parameters in the original getMax() function: getMax(4, 7).
Same order, yes, that means now 4 will be used as val1, and 7 as val2. After the function is done, it will return 7 since the first condition wasn't met (if (val1 > val2), or actually if (4 > 7)).
They're used to somehow have dynamic variables in functions.

How to write recursive function in MoonScript?

Is there something like arguments.callee of JavaScript for MoonScript?
Since Moonscript functions are defined as local func; func = function() end, they are all recursive. This will print 120:
recursive = (n) -> return n > 1 and n*recursive(n-1) or 1
print recursive 5
As far as I know, there is no arguments.calee alternative, but I haven't seen cases where I'd need it either. Even Mozilla's docs say "there are nearly no cases where the same result cannot be achieved with named function expressions" about arguments.callee.

Is there any direct function to get indices of all possible matches in an array

I generally find indexOf very useful, to get an index directly, and not writing 3-4 lines of for loop to get a match.
Is there any similar function, say like indicesOf , to get an array of all possible matches ?
Or may be having a different name, but acts as a shortcut as beautifully as "indexOf" ?
As you don't mind creating a new Array, you can use the filter() function - it executes a function on each item of the array, then returns a new Array with the items that return true:
// our comparison function
function myCompFunction( element:*, index:int, array:Array ):Boolean
{
return ( element > 10 );
}
var ar:Array = [5,10,15,20];
var ar2:Array = ar.filter( myCompFunction ); // ar2 is now [15,20]
It's not exactly indicies, but then again, you don't need to dereference your objects.
NOTE: because it's calling a function on each element, looping through the array yourself will still be quicker
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#filter()
Unfortunately, there is not such shortcut. indexOf works for only one item, and there is no alternative for multiple items.
The solutions are obvious - iterate over the entire array or use some kind of sort on the array. Maybe there are other methods, but they are almost the same - loop through everything and check. Sorry to say it, but that's the way it is :)

Custom sorting function bottleneck

I am trying to sort big array using actionscript 3.
The problem is that i have to use custom sorting function which is painfully slow and leads to flash plugin crash.
Below is a sample code for custom function used to sort array by length of its members:
private function sortByLength():int {
var x:int = arguments[0].length;
var y:int = arguments[1].length;
if (x > y){
return 1;
}else if (x < y){
return -1;
}else{
return 0;
}
}
Which is called like this:
var txt:Array = ["abcde","ab","abc","a"];
txt.sort(sortByLength);
Please advise me how can this be done faster ?
How to change application logic to avoid Flash plugin crashes during sorting ?
try to use strong typing whenever possible, here tell your function that you are waiting two strings.
you could rewrite your function in two way one fastest than the other if you know that all your element are not null:
function sortByLength(a:String, b:String):int {
return a.length-b.length // fastest way not comparison
}
and if you can have null check for it (this one will put null in front of all element):
function sortByLengthWithNull(a:String, b:String):int {
if (a==null) return -1
if (b==null) return 1
return a.length-b.length
}
If you need super-fast sorting, then it might be worthwhile not using an array at all and instead using a linked-list. There are different advantages to each. Primarily, with a linked-list, index-access is slow, while iterating through the list is fast, and linked-lists are not native to AS3 so you'll have to roll your own.
On the upside, you may well be able to use some of Polygonal Labs' code: http://lab.polygonal.de/as3ds/.
Sorting is very, very fast for nearly-sorted data with a linked list, as this article discusses: http://lab.polygonal.de/2007/11/26/data-structures-more-on-linked-lists/.
This solution gives you lots more work, but will eventually give you lots more sort-speed too.
Hope this helps.
-- additional --
I noticed your question in the comments of another answer about "One question however is unanswered - how to perform greedy computations in Flash without hanging it?"
For this, essentially the answer is to break your computation over multiple frames, something like this:
public function sort():void
{
addEventListener(Event.ENTER_FRAME, iterateSort);
}
private function iterateSort():void
{
var time:int = getTimer() + TARGET_MILLISECONDS_PER_FRAME;
var isFinished:Boolean = false;
while (!isFinished && getTimer() < time)
isFinished = continueSort();
if (isFinished)
removeEventListener(Event.ENTER_FRAME, iterateSort);
}
function continueSort():Boolean
{
... implement an 'atom of sort' here, whatever that means ...
}
sortByLength should have two parameters, shouldn't it? I guess that's what you mean by the arguments array...
This looks fine to me, unless arguments is not a local variable, but instead a member variable, and you're just looking at its [0] and [1] elements on each function call. That would at least produce undesired results.