Stupid. What are returns for, ie functions ect.
BlitzMax Forums/BlitzMax Beginners Area/Stupid. What are returns for, ie functions ect.
| ||
I've seen many function in the code archives that have return blah in them. In all the code I've ever written where I've used functions, I never thought of using the return statement. Maybe I'm not understanding fully what I'm doing, which is most probably the case. Can somebody explain why returns are used and why having a function without it works anyway? I know what you're all gonna say. I've been here 5 years and I still don't know how to program. :) I don't think I have the aptitude for coding. It's not gonna stop me though. I can code well to an extent but some things just refuse to make sense. Please don't make fun or start taking the p**s. :) |
| ||
Return is used to return the result of a function (where the function has a result). i.e. Function add:Int(num1:Int, num2:Int) return num1+num2 End Function print add(10, 200) As soon as the return command is issued, the function exits, passing the value provided. You can also call return on it's own to simply exit the function. |
| ||
Function Cos:Double( x ) What does COS do?It returns a value. HOw does it do this? At some point in the Function COS there is a "Return" What does it return? Well in this case A Double Whenever you want a function to return a value, even if this value is TRUE of FALSE for fail and success, the you use "Return" I fyou dont have a return, then the Function, simply jumps back to where it was called from when it reaches "End Function" Its the difference in old specrum talk between DEFFn which returns a value, and Gosub, which doesnt |
| ||
That makes sense. But this: I fyou dont have a return, then the Function, simply jumps back to where it was called from when it reaches "End Function" So using return doesn't make the function return to where it was called? If it doesn't then where does it go? |
| ||
Return does return back to where the function was called from. |
| ||
Return also return back to where the function was called from, but also returns a value |
| ||
I can't believe you've been programming for five years and have never used return! Half the point of functions are that they allow you to return a value... Here is simple example of how to use return: Function Add#(A#, B#) Return A#+B# End Function X# = Add#(10, 2) Here is another example. Note that you can use Return anywhere in the function and it will exit the function immeidatley and return that value. Specifying no return value with return will return false or 0. You can even use Return in functions that have no return type specified after the function name. Just don't put anything after the Return. Function GreaterThan%(A%, B%) If A > B Then Return True If A < B Then Return ' This returns 0 or False, which is the default value returned by Return. ' All functions behave as if the last line is Return, so if we get here because A = B, the function will still return False. End Function Note that if a function returns a value, you can choose to use it like a function that does not return a value and simply not assign it to anything. Ie, you could put: GreaterThan(10, 5) In your code, and there would be no error, even though GreaterThan is returning a value, and you're not passing that on to anything. A lot of times people make functions that do something like load a background image and instead of returning the image handle they might store that in some preprogrammed location and instead have the function return an error code... a boolean value... to tell them if the operation was successful. They might then choose to ignore that return value, or use it if failure is not an option. Ie: Function LoadLevel%(LevelName$) If the level loaded Then Return True End Function If Not LoadLevel("ep1lv1.wad") RuntimeError("Level failed to load!") End EndIf Hefully that makes it all clear. I'm still in shock over the return thing. I thought you coded a game or two. You did that without returning any values from functions? How long have you been coding? :-) I didn't use function returns in my first five years of coding either, but that's because I started coding in the 1980's and I don't think they even had C back then, or if they did it was only available on mainframes not home PC's. Basic back then had a line number on every line and gosub and goto statements instead of functions so if you wanted to return a value from anything you had to use a global variable... which was the only kind of variable back then. :-) Hey, I bet that's what you've been doing... Using globals to return the results of functions? I still do that sometimes because unless you return arrays you can only return one variable when you return something from a function with return. |
| ||
Hefully that makes it all clear. I'm still in shock over the return thing. I thought you coded a game or two. You did that without returning any values from functions? Yeah it's allclear now, thanks. I've been coding on and off for 5 years and I have never used returns in functions. :) so if you wanted to return a value from anything you had to use a global variable... That's what I do now. :) My code has globals all over the place. Thanks for all the help. :) |
| ||
"It is better to ask and appear ignorant than to remain ignorant" |
| ||
"It is better to ask and appear ignorant than to remain ignorant" I like this phrase. :) Newbie forum spamathon will begin soon. :) |
| ||
You can imagine that every function automatically has a Return on its last line anyway. For example,Function f() something {{{return}}} End Function It's always been there, you just never realised it ;) |
| ||
Apart from the obvious math'ish "return a+b" examples, another often used situation is returning true/false. If you have a player being able to move left and right until he bumps onto a wall, then you need to check that. You could write a function that checks the given xy pos from the player, and see if you can go there. What you get is something like: Function Check:Int(player:TPlayer,x:int,y:int) If MyMap[player.x+x,player.y+y]<10 Return true ' assuming <10 means walkable End Function And in your code: If Check(player,-1,0) GoLeft() If Check(player,1,0) GoRight() |
| ||
You can shorten the returns of boolean (true/false) functions futher. For example, instead ofFunction f():Int If condition Return True Else Return False End If End Function You can simply put Function f():Int Return condition End Function Or for CS_TBL's example, Function Check:Int(player:TPlayer, x:Int, y:Int) Return MyMap[player.x+x,player.y+y]<10 End Function Of course this will only work if nothing else happens if the section is not walkable. Remember that Return will stop the function there and then. So if you had code after the Return (perhaps a blocking sound or something) it would never get ran. In CS_TBL's example, if the condition is False the function will continue. There is nothing left so it would return False by default, but you could put code after the If statement that would run. |
| ||
Building on what CS_TBL said, if you notice, a lot of libraries, and particularly WinAPI stuff always return either True or False, indicating whether they were able to do what you asked or not. This can be very handy, and it's something I've done a bit in my own game engine. Czar Flavius' suggestion of shortening code with retutns can be useful too. EG: Function IsXLessThanTen(X:Int) Return X<10 End Function You just have to be careful to use it in situations where readability is not sacrificed for a few extra lines of code. IMO, the example I gave here does not compromise readability, indeed it probably aids it. So I tend to do that quite a bit too. |
| ||
Interesting, most cases have been mentioned but one not: Return will end the function immediately. This means if you check for a condition that needs to be met for further processing and it is not met, you can simply call return to leave the function. In those cases you normally return false or another special value to signalize the other code waiting for the function result, that the calculation failed. (depending on the function, you even return error codes) |
| ||
I never use Assert. If I have method to update the screen, if that update requires a map being present then: Method Update() If map=Null return ' draw map ' ' End Method which looks -to me- more logical than: Method Update() If map<>Null ' draw map ' ' End If End Method ..which saves you an indent! I wonder why Assert was made in the first place.. :P |
| ||
Interesting, most cases have been mentioned but one not: Return will end the function immediately. I said that already. |
| ||
Try thisFunction f:Int() Return f() End Function You'll need Task Manager to kill it. |
| ||
Now that you mention it, recursion hasn't been explained yet :P |
| ||
Now that you mention it, recursion hasn't been explained yet :P Haha, don't do that to him. Recursion used to make my head hurt. |
| ||
recursion is here: http://www.blitzbasic.co.nz/Community/posts.php?topic=69705 The tree is nice enough to toy with ^_^ |
| ||
Recursion is easy. :)function floodfill( x:int, y:int, color:int ) thiscolor = getpixel( x,y ) ' Save color under this pixel putpixel( x,y,color ) ' Paint over it ' Jump to pixels around this one if they have the same ' color this one used to have. if getpixel( x,y-1 ) = thiscolor then floodfill(x,y-1,color) if getpixel( x,y+1 ) = thiscolor then floodfill(x,y+1,color) if getpixel( x-1,y ) = thiscolor then floodfill(x-1,y,color) if getpixel( x+1,y ) = thiscolor then floodfill(x+1,y,color) endfunction Untested and written from memory using pseudo code. |
| ||
re·cur·sion –noun: See recursion |
| ||
cool thread...here's one for another bmax noob regarding Return... Function blah() for local A = 1 to 100 if a = 50 ; return True next end function Will the loop go through all 100 or stop at 50, and if it does stop at 50 and immediately exits, is it ok to code in this manner? |
| ||
it stops at 50. It is ok to code things that way |
| ||
Thanks deps! |
| ||
It's "ok" in that it won't be dangerous or unpredictable... but it is a bit pointless in your example lol. A return in the middle of a For loop isn't bad, and I have done it before. For example, say you were checking to make sure there was at least one type of element in a TList (similar to the other thread). The function returns true in the For loop as soon as it finds an instance, as there is no point carrying on the search. Or at the end of the For loop, it returns false. |
| ||
I'm using it to check for a collision, no need to carry on once the collision is found, this works great! ;) Thanks. |
| ||
OMG ;-) missed this one. I use Return sometimes mid function to abort out early. Really I should be setting some variable and returning that at the end for "clarity". I also use Return mid for loop quite often too. OR if I have more processing to do after the loop I set a variable and the use Exit. |