I keep getting surprised by the kind of questions no one has asked on these forums. Am I being thick, or does no one care to find out?
Anyway, I know what assert( ) and return do, but when should I use the first and when the latter?
Seems to me I should always use assert( ), as there is bonus error handling there, but something tells me if it’s not needed, return will be quicker. Is that right? [import]uid: 106739 topic_id: 18525 reply_id: 318525[/import]
I haven’t digested what it says there (I just glanced at it), but I thought I’d share the link with you. You might find it useful. From what I can tell by looking at the google results, it sounds like a very useful function/tool for debugging.
Assert’s job is to test for errors and crash the application with the error message. If there are no errors things are fine. This is a great debugging tool. But it and “return” are different beasts.
The job of return is to actually return a value or values (in Lua’s case) back to the calling program.
local function add(num1, num2)
return num1 + num2
end
print (add(1, 2))
So your caller gets a value back! Of course it’s okay to return nothing.
Assert on the other hand, tests for errors and if everything is okay, nothing else happens. You can’t do:
local function add(num1, num2)
assert( num1 + num2)
end
print (add(1, 2))
and get 3 printed. You will get a nil printed.
Hope this helps.
[import]uid: 19626 topic_id: 18525 reply_id: 71073[/import]
Oh I should add. I don’t use asserts. I don’t want my program to generate errors that crash it I’d rather test for it using an if statement and either provide some form of reasonable default value or return some code to the caller saying they screwed up.
[import]uid: 19626 topic_id: 18525 reply_id: 71074[/import]
Hey, Robmiracle, thanks for the very clear explanation (regarding the difference between assert and return)! Also, +1 for your comment posted on #3 above. I share the same thought process there.