How would I make a random for loop? This is what I am trying to achieve:
for 1,10 do math.random end
Though obviously math.random doesn't work due to the fact it isn't a number. So how would I achieve a random sequence?
This is the section of my script that contains the for loop I am talking about
for i = 0, List, 1 do LoadingBar.Size = UDim2.new(i/List, 0, 0.008, 0) Percentage.Text = tostring(math.floor(tonumber (i/List)*100)) .. "%" wait() if i == List then wait(0.5) BackgroundFrame:TweenSize(UDim2.new(1, 0, 0, 0), Enum.EasingDirection.In,Enum.EasingStyle.Quad, 1) wait(1) BackgroundFrame:Destroy() end end end)
I'm having trouble understanding your question, but I'll attempt to answer what I presume you mean to ask.
The for statement evaluates its provided expressions once, before the loop starts. With this in mind, we can provide a call to a random number generator as the numeric for's second expression to have it iterate until that number:
-- Create a new Random object. local random = Random.new() -- Output i for each value of i from 1 to a random number between 1 and 100. for i = 1, random:NextInteger(1, 100) do print(i) end
Note my use of the Random
class, which has a more random algorithm compared to math.random
and is recommended to be used.
You can learn more about the numeric for statement here.
I noticed that you provided an explanation of your question in the comments, so I'll describe how this can be achieved.
As I've previously said, all of the for statement's expressions are evaluated once, prior to the loop starting. For this reason, we cannot change the third increment expression every iteration—we'll have to create our own loop that's similar to the numeric for to provide this functionality:
local random = Random.new() -- Use a do block to limit the scope of used variables. do local start_n = 1 -- Start number. local end_n = 100 -- End number. local min, max = 1, 20 -- Minimum and maximum random number. local i = start_n -- Execute body and increment until i > end_n. while i <= end_n do -- ... i = i + random:NextInteger(min, max) -- Increment i. end end
Note that, with this script, min
and max
have to be integers and max
has to be greater than min
, else Random:NextInteger
will error. Changing this could be an exercise for you if you'd like to practice.