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.



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) |



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.



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!
[Please log in to post a comment]