When and why should I use the return command?

Sometimes when I look at code by other people I see either return nil, return, return 0 or something else.

What does it do and when should I use it?

[import]uid: 24111 topic_id: 14130 reply_id: 314130[/import]

if you call a function and it returns a value, it will give that value to the calling function. So if your main.lua looks like this:
[lua]local a=2

local b=function(a)[/lua]
if function(a) returns nil, b=nil. I use a return statement if i need to return some kind of state about how the function ended. for example, the previous function could be defined like this:

[lua]function(a)
if a<0 then return -1 end
if a> 0 then return 0 end
end[/lua]

Now, by the value of b, i will know if a is a negative number or a positive number. This is just an example.

also, the return statement can be used to exit a function prematurely.

hope this helps or is what you were asking.

-amanda [import]uid: 29997 topic_id: 14130 reply_id: 52003[/import]

Thanks! Now I understand why I should use it but exactly what do you mean with: “the return statement can be used to exit a function prematurely.” ?
[import]uid: 24111 topic_id: 14130 reply_id: 52004[/import]

for example:

[lua]local b=http.request(“url”)

–if b=nil, then don’t continue!
if b==nil then return end

–b ~= nil, then, parse the response, do something with it:

local x=parseXML.collect(b)

–do something with x[/lua]

If we did not check for b=nil, the program would crash. This way, we check for b==nil, if it does, return (don’t execute the rest of the function). also, you can return a value, and the calling function can know b=nil, and handle it accordingly.

-amanda [import]uid: 29997 topic_id: 14130 reply_id: 52007[/import]

amandavines,thanks for example [import]uid: 16142 topic_id: 14130 reply_id: 52008[/import]

Great example! Thanks! [import]uid: 24111 topic_id: 14130 reply_id: 52009[/import]

just an fyi, its considered bad programming practice to have multiple return statements in a function, mainly because it can be hard to keep up with them.

If you do, just be careful with your logic…

glad to help! [import]uid: 29997 topic_id: 14130 reply_id: 52010[/import]

Thanks for the tip! :smiley: [import]uid: 24111 topic_id: 14130 reply_id: 52012[/import]