Log In  

I'm trying to randomly select a value from an array.
I expected this to get me a random index in the array, but I'm getting the same every time.

 stmp={-130,50,500,1000,1500,2000,3000,3500}
 strt=rnd(#stmp)
 t=stmp[ceil(strt)]
 print(#stmp)
 print(strt)
 print(t)

Always prints:

8
0.5174 
-130
4.3404

I've used rnd() in other carts but I've never encountered this behavior before, please advice.

P#89940 2021-04-04 00:04 ( Edited 2021-04-04 00:04)

1

Do you have a srand() anywhere in your code? That sets the random number generator to a specific seed, so it will always produce the same sequence of "random" values.

If you want a random value from a table, you can just pass the table to the rnd() function and it will give you back a random value. Like so:

stmp={-130,50,500,1000,1500,2000,3000,3500}
t=rnd(stmp)
P#89946 2021-04-04 01:14

Copying just that excerpt into PICO-8 seems to be producing random numbers for me - do you use srand() to set a seed somewhere else in the code? Or set a variable called rnd to a value somewhere?

(Also, I think there might be a subtle bug unrelated to what you're seeing - according to the manual, rnd(x) can return a 0, so about one time in 65536*#stmp you're going to get t=stmp[0]=nil and probably a crash. Using t=flr(rnd(x))+1 instead would fix that.)

Edit: Sniped by MBoffin with the better suggestion! I forgot about the rnd(table) thing.

P#89945 2021-04-04 01:14 ( Edited 2021-04-04 01:15)

Oh wow thanks, there indeed was an srand just before my statement.
Thanks alot for clarifying, I was really tearing my hair out =D
Cheers!

P#89960 2021-04-04 09:41

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-04-18 06:06:50 | 0.010s | Q:14