Difference between "return" and "return true"?

I feel stupid even asking this, but it’s a little hazy and I want to clarify it… what’s the difference between:

return

and

return true

I understand that they both basically stop and “exit” a function. But what is the purpose of adding “true” versus not adding it?

Thanks!
[import]uid: 9747 topic_id: 9319 reply_id: 309319[/import]

I add true to my return statement if I want to check how the called function returned, or ended.

When I have a return true, I only return true when everything ran as expected, any other path through the function, that isn’t as expected, will return false. [import]uid: 5317 topic_id: 9319 reply_id: 34058[/import]

“return” alone is equivalent to “return nil”.

[lua]function doSomething()
if iWannaQuit then
return
end
end

function isEverythingAlright()
if iAmRich and iAmHappy then
return true
else
return false
end
end

a = doSomething() – a = nil
everythingAlright = isEverythingAlright() – everythingAlright = false[/lua] [import]uid: 51516 topic_id: 9319 reply_id: 34070[/import]

Functions can give a result when they finish. Saying “return true” means the returned result is “true” whereas just saying “return” means there’s no result.

seth’s code demonstrates functions returning results from functions. At the very bottom try print(a) and print(everythingAlright) to see the results. [import]uid: 12108 topic_id: 9319 reply_id: 34125[/import]

Thanks to all who responded! I now understand this “return true/false” difference. :slight_smile:
[import]uid: 9747 topic_id: 9319 reply_id: 34131[/import]

Be careful as there is a subtle difference between “return” and “return nil”:

[lua]local f1 = function() return end
local f2 = function() return nil end
local f3 = function() return false end
local f4 = function() return true end
local ff = function(…) print(select("#",…),",",select(1,…),",", select(1,…)) end
ff(f1())
ff(f2())
ff(f3())
ff(f4())[/lua]

yields:

[lua]0 , nil ,
1 , nil , nil
1 , false , false
1 , true , true[/lua]

Which seems to imply that “return” truly doesn’t seem to return anything, which is different from “return nil”, where the latter returns a real nil. Most of the time that difference is not visible, unless you count argument-values with select.

Just one of those nasty nil-gotchas in Lua that can bite you when you don’t expect it…

-FrankS. [import]uid: 8093 topic_id: 9319 reply_id: 35664[/import]