Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why can't I randomize a number?

Asked by 10 years ago

This is a very simple script, yet it seems to have a glitch.

local cue=script.Parent.Music:GetChildren()
local r=math.random(1,#cue)
local song=cue[r]

It returns no errors, but it always returns 1, which is the very first song. Then it plays the second, then the third, and so on. I want it to choose randomly, but the math.random function always returns 1.

0
Try printing out `#cue` after you initialize what cue is. Is it always 1? User#2 0 — 10y

2 answers

Log in to vote
0
Answered by 10 years ago

Well, math.random will ALWAYS return the same numbers. For example, if you ran:

for _ = 1, 10 do
    print(math.random(100))
    wait(1)
end

It would print the same 10 numbers every time. To fix this, you need to use math.randomseed(tick()). That would return different numbers every time the place ran. Read more on the wiki here.

1
Incorrect. math.random will return a new number (presumably it sets the seed to something else upon calling, though I wouldn't quote me on that) upon calling it multiple times. User#2 0 — 10y
0
Read the wiki article. SlickPwner 534 — 10y
0
I've tested it and it does return different numbers. Proof: http://imgur.com/IO7hALz Gamenew09 180 — 10y
0
Same 10 numbers everytime means it will print the same sequence of numbers everytime. What SlickPwner said is correct. gskw 1046 — 10y
0
Studio is giving me different numbers upon different runs, I disagree that it is necessary to set randomseed. BlueTaslem 18071 — 10y
Ad
Log in to vote
-1
Answered by 10 years ago
local songs = {} -- empty table so we can insert the names later
local song -- call the variable song as nil just for cus :P
for _, v in pairs(script.Parent.Music:GetChildren()) do -- loop through the Music thingy
    table.insert(songs, v.Name); -- inserts each child's name in the songs table for later usage
end

song = tostring(songs[math.random(1, #songs)]); -- now we us the variable song and tell have it be a random song!

Answer this question