what is a good way to run a group of code for a certain amount of time without stopping other code, I did this with a for loop before but I knew less back then and I think coroutines would work better
what is a good way to make it so I can do
local module = require(module)
module.Touched:Connect(function()
- would run code whenever the module calls the Touched event
end)
yes ik there is a module that does number 2 but I want to do this on my own without other modules
any help would be appreciated, also I didn’t find much on number 1
The coroutine library is perfect for this. For simple usage, you can just do something like:
coroutine.wrap(function() -- Create a function that "has" a coroutine
-- Code here...
end)() -- Call said function
If you want to stop the coroutine at some time, you can use coroutine.yield:
local function threadFunc()
for i = 1, 10 do
print(i)
wait(1)
end
end
local thread = coroutine.create(threadFunc)
coroutine.resume(thread) -- run the coroutine
wait(5)
coroutine.yield(thread) -- stop the thread right there about halfway
print(coroutine.status(thread)) -- should be 'suspended'
sorry but that runs code every second 10 times
I want to run code nonstop for a certain amount of time
sort of like a for loop but you can choose seconds instead of how many times it runs
local module = {} -- create a new empty table
local touched = Instance.new('BindableEvent') -- create a new bindableevent
module.Touched = touched.Event
function module.something(part) -- add a function
touched:Fire(part) -- fire the bindable event
end
return module -- once this module is required it will return a table with our function and event
local myModule = require(path.to.module) -- get the module
local object = Instance.new('Part') -- create a new part
object.Name = 'newPart'
object.Parent = workspace
local connection = myModule.Touched:Connect(function(part) -- connect the event
warn(part.Name)
end)
wait(6) -- wait a few seconds
myModule.something(object) -- call the function inside our module
connection:Disconnect() -- disconnect the event
local RunNSeconds(n)
local Thread = coroutine.wrap(function()
while true do wait()
print(“I got printed for ”..n..” seconds”)
end
end)()
wait(n)
coroutine.yield(Thread)
end
RunNSeconds(2)
yes ik wait() isn’t reliable for everything but this was an example
I can’t test this rn so would this work well for my first question???