Defaulted Value Not Being Applied

Monkey Forums/Monkey Bug Reports/Defaulted Value Not Being Applied

c.k.(Posted 2012) [#1]
[monkeycode]
Class Test
Field a:Int = 3

Method TestMethod:Void(b:Int = a)
Print a
Print b
End
End

Function Main()
Local x:Test = New Test
x.TestMethod
End

[/monkeycode]

gives me this result:

3
undefined


but it should be

3
3


from what I understand.

What's the problem?


DGuy(Posted 2012) [#2]
Hi,

I'm pretty sure most languages require default parameter values to be constants.

It has to do with when things get evaluated: The field 'a' does not come into existence until new'd up at run-time, while the functions signature need to be known before then.

I think Monkey should be complaining here ...


c.k.(Posted 2012) [#3]
It works for functions/global vars:

[monkeycode]
Global c:Int = 5

Function TestFunc:Void(b:Int = c)
Print "TestFunc:"
Print "Global c = " + c
Print "Local b = " + b
End

Class Test
Field a:Int = 3
Method TestMethod:Void(b:Int = a)
Print "TestMethod:"
Print "Field a = " + a
Print "Local b = " + b
End
End

Function Main()
Local x:Test = New Test
x.TestMethod
TestFunc()
End
[/monkeycode]

When Class Test is created, isn't 'a' defined at that point and can be used subsequently? Will Method New() help...? Let's find out!


c.k.(Posted 2012) [#4]
[monkeycode]
Global c:Int = 5

Function TestFunc:Void(b:Int = c)
Print "TestFunc:"
Print "Global c = " + c
Print "Local b = " + b
End

Class Test
Field a:Int
Method New()
a = 3
End
Method TestMethod:Void(b:Int = a)
Print "TestMethod:"
Print "Field a = " + a
Print "Local b = " + b
End
Method TestMethod2:Void(b:Int = c)
Print "TestMethod2:"
Print "Global c = " + c
Print "Local b = " + b
End
End

Function Main()
Local x:Test = New Test
x.TestMethod
x.TestMethod2
TestFunc()
End
[/monkeycode]

Nope. :-/

This is a bug. It's gotta be! :-)


therevills(Posted 2012) [#5]
Yeah I seen this too and the workaround is to set up the variables in the methods.

I agree that it looks like a bug to me.


slenkar(Posted 2012) [#6]
Are you allowed to assign variables in the function arguments?

TestMethod:Void(b:Int = a)



c.k.(Posted 2012) [#7]
Yes, because c is assigned to b in TestMethod2 (IIRC).


DruggedBunny(Posted 2012) [#8]
I'm surprised Monkey allows that, to be honest, and wonder if that is a bug rather than what you're reporting!

Just checked, and BlitzMax certainly says no:

' Max code!

Type Test

	Field b = 1
	
	Method Tester (a = b)
		Print a
	End Method
	
End Type

Local t:Test = New Test
t.Tester


This throws "Compile Error: Function defaults must be constant".