Accessing a member variable before declaring a variable that would overshadow returns null
Godot version
4.0-dev.20211108
System information
Ubuntu20.04,headless,HD Graphics 530
Issue description
I'm using Callable in Godot4.The following code works well:
func test():
print("in test")
func _ready():
print("_ready:")
print(test)
test.call()
output:
_ready:
Node(Node2D.gd)::test
in test
But when I write this:
func test():
print("in test")
func _ready():
print("_ready:")
print(test)
print(typeof(test))
var test=12
Output:
_ready:
null
0
Similarly, when I get a function with the same name before a variable declaration, I get null
Is it working properly?
If my grammar is OK,Why do I get null instead of Callable? Is my grammar wrong? Godot4 doesn't have any reminders!
Steps to reproduce
run this in 4.0.dev
func test():
print("in test")
func _ready():
print("_ready:")
print(test)
print(typeof(test))
var test=12
Minimal reproduction project
No response
Production team edit: added highlighting
Similarly, when I get a function with the same name before a variable declaration, I get null
It looks like local variable declarations affect the whole function/block. That is, your code is actually:
func test():
print("in test")
func _ready():
var test # (It happens implicitly.)
print("_ready:")
print(test)
print(typeof(test))
test = 12
Probably, the compiler should print an error/warning "Using a local variable before its declaration".
Use self.<name> to access the class members if the function has a local variable with the same name.
There is already a warning about shadowing method/variable names (the example code here shows one too), so the solution is to not use conflicting names,
Similarly, when I get a function with the same name before a variable declaration, I get null
It looks like local variable declarations affect the whole function/block. That is, your code is actually:
func test(): print("in test") func _ready(): var test # (It happens implicitly.) print("_ready:") print(test) print(typeof(test)) test = 12Probably, the compiler should print an error/warning "Using a local variable before its declaration".
Use
self.<name>to access the class members if the function has a local variable with the same name.
@dalexeev yes,I see.But that's strange! When I use such code:
func _ready():
print("_ready:")
print(val)
var val=12
Output:
ERROR: Parse Error: Identifier "val" not declared in the current scope.
at: GDScript::reload (res://Node2D.gd:10)
ERROR: Method/function failed. Returning: ERR_PARSE_ERROR
at: reload (modules/gdscript/gdscript.cpp:855)
it's ERROR!!! So I can't use a variable before declaring it!!! Godot does not move variable declarations to the front! So if this is true, when will Godot move the variable declaration to the front?
With #79880 this will work as expected, but will generate warnings.
func test():
pass
func _ready():
print(test) # Node(node.gd)::test
print(typeof(test)) # 25
var test = 12
print(test) # 12
print(typeof(test)) # 2