Let's say I want to preform an action 15 times in a second. I want to make sure the action was preformed exactly 15 times in exactly 1 second. How do I do that?
I've tried this:
local oldTime = os.time(); local amount = 15; local iteration = 1; while os.time() == oldTime do wait(1 / amount); iteration += 1; end; print(iteration)
If you don't know what it does, there is a loop that only lasts for 1 second, and it waits 1 15th of a second and adds 1 to a variable until a second has passed
But when I print the variable that was supposed to be 15 from adding, it's almost never 15.
By evenly split out, I mean I want the action to be done all at the same time, I want the actions to be done split evenly out the second.
(I'm doing a different action, not increasing a variable. I just did that for the example)
This can be achieved with a for loop.
A for loop runs code a certain amount of times, and to wait in-between you just use wait().
local amount = 15; local iteration = 0; for count = 1,amount do wait(1 / amount); iteration += 1; end; print(iteration)
In this example it runs your code 15 times. Adding 1 to the "iteration" variable every 1/15 of a second. Also I set iteration to 0 because it ran 15 times and iteration would be 16 if it started as 1. Hopefully I didn't misunderstand and hopefully it helped!
You can learn more about for loops here: https://developer.roblox.com/en-us/articles/Loops
Using os.time() == oldTime is very unreliable, as the oldTime could be something like 100000.5 and os.time() could be 100001. Meaning, it has only .5 seconds to take those 15 actions.
There's a simple solution to this. You just add + 1 second to oldTime and check if os.time() is lower or equal to oldTime.
As for the 15 actions, you need to check if iteration == 15.
local oldTime = os.time() + 1; local amount = 15; local iteration = 0; while os.time() <= oldTime do wait(1 / amount); iteration += 1; if iteration == 15 then break end end; print(iteration)