Usage of "return" and its differences?

OK, I feel like a complete moron for even asking this, especially having tinkered with JavaScript and TorqueScript before coming to Lua…

Basically, I’ve never fully understood the use of “return” at the end of a function. Seems like the most novice question, but it’s time that I understand it fully. :slight_smile:

So in the following sample snippet:

local function killOneEnemy ( enemyCount )  
 local newEnemyCount = enemyCount - 1  
 return newEnemyCount  
end  

This “returns” the updated enemy count, correct? But returns it to where/what? To another function that called this “killOneEnemy” function? Where does the returned value get sent to? What happens to it? How can I use it?

And then consider a basic “return” with no value:

return  

What purpose does this serve? Return nothing? Does it “end” the function, like a flow break?

Finally,

return true  

This does what? Returns “true”? What is true , an arbitrary boolean? How does the language interpret/use this? Why does adding “return true” to the end of a function in Corona effectively “stop” other functions, i.e. when you have a button, it processes only that button and prevents any actions in groups/layers below it?

Argh, this should be so simple, but for some reason I’ve never fully understood the “return” code, not in Javascript, TorqueScript, nor Corona. I understand how to pass variables to functions, but I’m not really sure how to retrieve them and use them.

Any help is appreciated, I’m sure somebody can clarify it for me easily…

Brent

[import]uid: 9747 topic_id: 2821 reply_id: 302821[/import]

Hi Brent,

I will try to shed some light with a simple example.

[lua]function myAdd(a,b)
local result
result = a + b
return result
end

local sumvar
sumvar = myAdd(4,5)
print(“sumvar=”…sumvar)
print(“12+6=”…myAdd(12,6))
print(“false=”,false)
print(“true=”,true)[/lua]

The result of a function can either be assigned to a variable, or as a parameter of another function.
Booleans are not 0 and 1 like in other languages. They are TRUE or FALSE, just that. [import]uid: 5712 topic_id: 2821 reply_id: 8406[/import]

Even simpler:

[lua]function ret()
return 123
end

value = ret()
print(value) – prints: 123[/lua]

If you see “return true” that means the function returns true, a boolean. You can also return a string or any data type:

[lua]function ret()
return “a string”
end

value = ret()
print(value) – prints: a string[/lua]

And a single return with no parameter simply exists the method at that point. You can use that for control flow, however a return in the middle of a function is often considered difficult to debug. I prefer to simply break out of the inner loop. If you can’t do that easily in a function, it’s a good sign the function is too big and does more than one thing, in that case it should be refactored. [import]uid: 10479 topic_id: 2821 reply_id: 8809[/import]