In this code:-
if (myTest)
{
var myVar:Int = 1;
}
else
{
myVar = 2;
}
the second reference to myVar
is undefined.
This is due to myVar
being only defined in the scope of the first block.
But where is this documented and what is it known as?
kLabz
(Rudy Ges)
December 5, 2018, 8:12am
2
var myVar:Int = 1
and myVar = 2
are in two different blocks (and the later is not in a sub block of the former)
There is an entry in the manual about blocks: Blocks - Haxe - The Cross-platform Toolkit
Did not find one about variable scope (ok that’s because var and final - Haxe - The Cross-platform Toolkit links to this entry for the “scoping behavior of local variables”).
1 Like
“Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).”
— somewhere on the internet
Haxe doesn’t have this variable hoisting, every block creates its own scope.
The following doesn’t answer the question at all, but you can also do this in Haxe:
var myVar = if (myTest) {
1;
} else {
2;
}
of even shorter
var myVar = if (myTest) 1 else 2;
Confidant
(Allan Dowdeswell)
December 7, 2018, 5:14pm
4
Or shorter still:
var myVar = (myTest) ? 1 : 2;
kevinresol
(Kevin Leung)
December 15, 2018, 5:18am
5
or even even shorter:
var myVar = myTest ? 1 : 2;
lol in that case I can even go shorter
var m=myTest?1:2;
kevinresol
(Kevin Leung)
December 22, 2018, 2:57pm
7
@mark.knol I just want to point out the EParenthesis
expression is not necessary. Same for that in switch (o) {}
.
1 Like