I've been reading the wiki, and it says that it's wait
function is pretty much based around coroutine.yield
. Just wondering, what would this function look like? Could anyone give an example of what it would be like to create an "artificial" wait function with ROBLOX Lua using coroutine.yield?
A custom wait function can be made in 2 ways:
By default, every thread, except ones created with the coroutine library are ROBLOX threads. Since you want a custom wait, I assume you want to use it in coroutines. You'll have to use some kind of yielding (except co.yield) in your thread scheduler though. The easiest way would be wait(), but on the client you could use RenderStepped:wait() etc. I'm gonna use wait() here since that's easier to write
You'll first need a task scheduler for that:
local threads = {} local function startthread(func,...) local th = coroutine.create(func) table.insert(threads,th) return coroutine.resume(th,...) end spawn(function() -- Here is more or less the actual scheduling for k,v in pairs(threads) do if coroutine.status(v) == "dead" then -- The thread has ended (error or function returned) threads[k] = nil else -- Thread is still alive, let's resume it local s,e = coroutine.resume(v) if not s then -- Make sure we know it errored warn("Thread error:",e) end end end end)
Your custom wait would be in all cases something like this:
function wait(t) t = t or 0 -- default is 0 seconds local start = tick() local stop = start + t repeat coroutine.yield() until tick() > stop -- Return the time we waited + that second thingy of wait return tick()-start,tick() -- #2 isn't tick(), but nobody knows end
How this works: Start a thread by calling startthread(FUNCTION,ARG1,ARG2,...) Your wait function will yield the current coroutine. (the repeat loop) Your task scheduler will resume (all) the thread(s) every wait(). Your wait function gets resumed and checks if it waited long enough. If it didn't, it'll just yield again and again, until enough time has passed.
Note: If you use wait() inside the new thread, your thread will become a ROBLOX thread. (Which means, the thread is added to ROBLOX' internal thread scheduler) This would make roblox auto-resume the thread the whole time.
Just stick with wait(), it's the easiest, it works, and you don't need a custom 99.99% of the time
As you know it takes time for everything in a program to run. This is called runtime.
If you run a loop you extend the runtime depending on how many times you run the loop. So say the time it takes for you to run a loop like:
for I = 1,2 do end
takes only 0.3 seconds (which is extremely long). If you run this program approximately 3 1/3 times it would add up to a second. This is what the wait() function does in a nutshell but with very precise timing. Yield on the other hand runs a infinite loop. This is my theory on how loops work in roblox lua.