See this thread about returning values that do not yet exist.
The return on line 7 returns from the function on line 7, not the showMSG function.
You can't forcibly return from another function, because that function may no longer be running (or may be recursive, etc...)
There are roughly three broad options:
1. Blocking
Don't return until you have an answer.
This is a little awkward to do in ROBLOX for this particular case, but it's possible and not too bad with BindableEvents.
function showMSG(gui)
gui.Enabled = true
local event = Instance.new("BindableEvent")
local yesEvent = gui.Yes.MouseButton1Click:Connect(function()
event:Fire(true)
end
local noEvent = gui.No.MouseButton1Click:Connect(function()
event:Fire(false)
end
local answer = event.Event:Wait()
yesEvent:Disconnect()
noEvent:Disconnect()
return answer
end
local answer = showMSG(foo)
print("Player said", answer)
2. Promise / Future
Return an object that can be used to produce an answer.
The simplest way to do this is to return an event:
function showMSG(gui)
gui.Enabled = true
local event = Instance.new("BindableEvent")
local noEvent, yesEvent
yesEvent = gui.Yes.MouseButton1Click:Connect(function()
event:Fire(true)
yesEvent:Disconnect()
noEvent:Disconnect()
end
noEvent = gui.No.MouseButton1Click:Connect(function()
event:Fire(false)
yesEvent:Disconnect()
noEvent:Disconnect()
end
return event.Event
end
local answer = showMSG(foo):Wait()
print("Player said", answer)
3. Callback / Continuation
When you invoke showMSG, tell it to contact you later.
This is usually the least convenient way to write code because it leads to lots of functions nested into each other, but it is an option.
function showMSG(gui, callback)
gui.Enabled = true
local event = Instance.new("BindableEvent")
local noEvent, yesEvent
yesEvent = gui.Yes.MouseButton1Click:Connect(function()
yesEvent:Disconnect()
noEvent:Disconnect()
callback(true)
end
noEvent = gui.No.MouseButton1Click:Connect(function()
yesEvent:Disconnect()
noEvent:Disconnect()
callback(false)
end
end
showMSG(foo, function(answer)
print("Player said", answer)
end)