while configuration.GAME_RUNNING do
for _, player in pairs(players:GetPlayers()) do
local character = player.Character
if not character then return end
end
end
I have a really long script that seems to break randomly. I am wondering, if I have this, and if the character isn’t there, would the return exit the while loop? Being run server side as well. I can post the whole loop if need be, but it’s quite long and it works like 50% of the time, so figured it might have something to dow ith these returns
Return is used to immediately stop execution of a function and return a value back to where it was called from. This means it will break all loops contained in the current function call. If you want to break out of a single loop you need to use the break statement instead.
No, the while statement will stop and the enclosing function will be returned from. You can alternatively use break to break from just the enclosing loop.
return is used to return a value and/or prematurely end the function. So yes the entire loop would break.
You should simply not do anything if there isn’t a character.
while configuration.GAME_RUNNING do
for _, player in pairs(players:GetPlayers()) do
local character = player.Character
if not character then
-- # nothing
else
-- # do what you do
end
end
end
All functions in Lua have a return explicit or implicit. As magnalite said return will immediately stop the execution of the function and the values are passed back to where the function was called from.
The code cannot continue after this point as the calling function now needs to run. All execution of code in the calle function will halt at calling the return.
The most common example I would say in Roblox is a debounce
local deb = false
something.Changed:Connect(function()
if deb then return end -- prevent code from running
deb = true
...
deb = false
end)