Basically I have two scripts, script A and script B. In script A I require script B which has a function that returns a value. However, this value only gets returned when a button is clicked. I was wondering how to yield script A until script B returns that value. I’ve tried coroutines but they didn’t seem to work out for me, maybe I was just doing them wrong. I also looked around but couldn’t find much related to my issue. Any help would be nice, thanks!
Example of the first script
local ReturnedValue = require(script.OnClick)
local Value = ReturnedValue()
print(Value) -- Nil
return function(Button)
task.wait(10)
return 'This value will be nil'
end
local ReturnedValue = require(script.OnClick)
local Value = ReturnedValue()
repeat wait() until Value ~= nil --This will yield the thread until the value no longer is nil.--
print(Value) -- Nil
In the example you provided, when you call the function from script B, the current thread of script A will yield until this function returns but if this function was wrapped into another thread like task.spawn for example, the thread of the script A will continue to work without yielding.
I don’t exactly know the goal; can you explain more context?
This doesn’t seem to be the case. When I print the returned value from the module it prints nil and the script just keeps going on. I could give the actual code example if that would help you out more.
I tested your code examples, a script that requires a module script which does return a function upon requiring, executing the returned function should yield the script’s thread
(10 secs) until the value "This value will be nil" is returned.
Perhaps it is because I’m returning something in an event. I simply thought using that as an example would work but here is what it actually looks like.
local dosomething = require(script.ModuleScript)
local button = game.Players.LocalPlayer.PlayerGui:WaitForChild('Test').TextButton
local value = dosomething(button)
print(value)
return function(button)
button.MouseButton1Up:Connect(function()
return 'value'
end)
end
Well the module creates some buttons and a frame for me. It also sets a MouseButton1Up event to each button. It’s really just to make the code look neater.
why not make a function in the module script where you provide the button that you want to be clicked and the callback that you want to be called, something like this
module:OnButtonClicked(Button : Instance, CallbackFunction)
Gui[Button].MouseButton1Down:Connect(CallbackFunction)
end
idk how your gui is set up but this is just an example ^
I don’t believe this would work for me considering I create buttons in a loop each with their own event. Unless I could somehow tell the module to return outside of that loop but I have no clue