return from Function not working?

BlitzMax Forums/BlitzMax Beginners Area/return from Function not working?

lotonah(Posted 2006) [#1]
Hi there...this isn't the exact code, but close enough (for brevity).

'Main
Global Plyr1 :int=0
Global Plyr2 :int=0
Global Winner :int=0

Plyr1=0
Plyr2=1
LogicModule()
print Winner
waitkey
End

Function LogicModule()
Winner=0
if Plyr1=0 and Plyr2=1 then Winner=1
return Winner
end function

Now, if I put the print inside the function, it will print a 1. When I put the print after the function call, it prints a 0. I'm assuming it's something to do with the RETURN not properly passing Winner back to the main program?

Help would be appreciated. Thanks!


TomToad(Posted 2006) [#2]
Prints 1 here.
Try putting superstrict at the top of your code. I bet in your source, you misspelled "winner" somewhere. Maybe winer, or wniner or something like that. Using Superstrict will show you where such errors occur.


JazzieB(Posted 2006) [#3]
You don't need to return anything from your Function (as it is above), because you have set Winner to be a Global variable, which is visible to the entire program regardless of whether it's in a Function or not. Take out the 'Return Winner' line from your Function.

On the other hand, if you need the Function to return Winner, you should assign the output from LogicModule to your Winner variable, as follows:

' Main
Global Ply1:Int=0
Global Ply2:Int=0
Global Winner:Int

Ply1=0
Ply2=1
Winner=LogicModule()
Print Winner
WaitKey
End

Function LogicModule()
  Winner=0
  If Ply1=0 And Ply2=1 Then Winner=1
  Return Winner
EndFunction

Having said all that, the code posted above should work, so you may have made a mistake elsewhere that causes the value of Winner to get changed.


ImaginaryHuman(Posted 2006) [#4]
You haven't defined that it WILL return anything.

In your function declaration you have to specify the TYPE of data that will be returned.

Function LogicModule:Int()
...
End Function


JazzieB(Posted 2006) [#5]
You only need to define the return Type if using Strict or SuperStrict modes. If not, then Int is assumed as default.


ImaginaryHuman(Posted 2006) [#6]
Oh, cool.


lotonah(Posted 2006) [#7]
Hey, thanks guys, it works now. Actually, turning on STRICT mode helped uncover a few other problems too.

In the end, I did the following changes:

Winner=LogicModule() (JazzieB's suggestion)
&
Function LogicModule:Int() (AngelDaniel's suggestion)

The combination did it. You guys rock!


Brucey(Posted 2006) [#8]
You might want to consider using Superstrict too. It makes for stronger code and is much less prone to you having a silly bug that you miss when you are hunting down issues - especially with the "everything defaults to int if you don't say what it is" thing.

Also, if anyone else is likely to have to look at your code at some point, using Superstrict will have meant you've "typed" all your variables, and it's easier for them to see what is going on.

:-)