Haiku Using Random Class in HH Scripting

neillt

Active Member
Lupinglade and anyone else who might be able to help here....
 
I am trying to generate a whole-house vacation mode script to turn on random lights for random intervals during night time to give the house a "lived in" look.
 
The trouble I am having is with the Random class, I can't seem to figure out how to call it to generate a new Random object.
 
Stack Overflow had a good example of:
 

public static int randInt(int min, int max) {

// Usually this can be a field rather than a method variable
Random rand = new Random();

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;

return randomNum;
}

But this is for full-blown Java, not scripting.  I have also tried using the Math.random method but that's crashing HaikuHelper when I call it.
 
So in the end, what method do I use to generate a random number?
 
Have some time this weekend to work this... here is what I have (Version 4.01 (401)):
 

// First is generate a random number for timing light durations while in Vacation Mode
// This will only generate numbers between 1 and 90, meant for minute timers.

function generateVacationLightDuration() {
rand = new Random();
randomNum = rand.nextInt((90 - 1) +1)+1;
return randomNum;
}

The other functions are the same, just with a different function name and possibly a different max amount.
 
OK, using Math.random is crashing HH.  Here is the button press script that's letting me test it, other button code is removed:
 

function onButtonActivate(button){
if (button.number == 9) {
helper.log (controller,"Button 9 Pressed");
helper.log (controller,"Generating random.... results are "+generateVacationLightDuration());
}

}


Here is the generateVacationLightDuration script:
 

function generateVacationLightDuration() {
// this is the new code using Math.random
Math.floor((Math.random()*90)+1);
return randomNum;
}

If I just log that button 9 was pressed, no problem.  If I perform the Math.random call, it crashes HH.
 
Well, OK.  I figured it out.  Programming 101.  Two problems, really.
 
1) The math library calls all give non-string returns.  So you have to convert to string to log.
 
2) When I changed to math.Random I forgot to return the variable correctly.
 
I changed those 2 things and now it's working.... but it might be helpful to have some better error handling than just an app crash ;-)
 
It looks like you were also returning an undefined variable. The code above is not assigned to the variable you are returning in generateVactionLightDuration
 
Back
Top