why does this compile?

Monkey Forums/Monkey Bug Reports/why does this compile?

ziggy(Posted 2012) [#1]
Function Main()
	Local a:String = 0
	For Local a:String = "A" to "Z" step 1
		Print "Iteration value is " + a
	Next
End

Isn't it weird?


Paul - Taiphoz(Posted 2012) [#2]
it must be treating the initializing zero as a character because you have defined it as a string even though you aint surrounded it with quotes.


JIM(Posted 2012) [#3]
I think the fact that the for loop compiles is more interesting. Does it output the letters correctly?

If so then it might just treat is as char in the loop and as a string in the "Print" command.

Still kinda weird and completely against readability I might add :)


DruggedBunny(Posted 2012) [#4]
Gotta be a bug! Moving thread...

Warning: This code slows Monk to a crawl for me (STDCPP)!


ziggy(Posted 2012) [#5]
No, on Java it is creating attaching a literal "1" on each iteration.

the initialization is correct as Monkey does perform automatic conversion from numeric types to strings (so you can do things like Print(4). I was just trying a funky For/Next syntax to see what happened and suddently saw that the compiler was accepting it, so I was curious if I was misunderstanding any language feature, or it was just a type checking bug on the compiler.


marksibly(Posted 2012) [#6]
Hi,

It's kind of correct, but kind of useless too.

Basically, since these code fragments are all valid, so is the for loop:

Local t$="A" 'init index var
If t<"Z" Print "Yes!" 'compare index var with to/until value
t+=1 'increment index var

In fact, here's a 'useful' example:

	For Local t:="A" Until "AAAAA" Step "A"
		Print t
	Next


Ok, not so useful! This should probably get fixed, although it doesn't actually bug me that much...


ziggy(Posted 2012) [#7]
The thing that was really looking strange is the automatic conversion of the step to string, I mean, the operation should be a mathematical increment, not a concatenation. it looks like a bug. The fact that we use + for both concatenation of strings and adding numerals does not mean they are the same operation and IMHO this should not be legal on a For loop. Not in the form of a concatenation, maybe as an addition in the char index of the string or something like this, dunno. Anyway, it's ultra weird.


JIM(Posted 2012) [#8]
Well, if you translate this to a C-style for, it will make more sense I guess:

for (string t = "A"; t < "AAAA"; t += "A")


Since "+" is overloaded for strings to concatenate, you get just that. Even if you put 1 for step, for strings, "+"-ing with an int concatenates with the int converted to string.

It does make sense, it's just not that useful and might be hard to understand right away if actually used in code.