Godot Version
` v4.3.stable.official [77dcf97d8]
Question
I’m having trouble with Array-typed arguments to a lambda function. Passing them to a regular function seems to work fine, but with a lambda the parser complains that the type is wrong. e.g.:
@tool
extends EditorScript
func print_arr_func(a:Array[int]):
print(a)
func _run() -> void:
print_arr_func([1,2,3])
var print_arr_lambda = func(a:Array[int]): print(a)
print_arr_lambda.call([1,2,3])
var print_arr_func_lambda = print_arr_func
print_arr_func_lambda.call([1,2,3])
The call to print_arr_func works fine.
The call to print_arr_lambda complains about a type mismatch:
Invalid type in function '<anonymous lambda>(lambda) (Callable)'. The array of argument 1 (Array) does not have the same element type as the expected typed array argument.
And the call to the function as a lambda fails in the same way:
Invalid type in function 'EditorScript(arrayarg.gd)::print_arr_func (Callable)'. The array of argument 1 (Array) does not have the same element type as the expected typed array argument.
If I make the array argument untyped, it works fine.
var print_arr_untyped_lambda = func(a:Array): print(a)
print_arr_untyped_lambda.call([1,2,3])
Is this working as intended? I would expect lambdas to support all of the types as regular functions. Or am I doing something wrong?
This conversation on GitHub seems relevant. It seems like the [1, 2, 3]
in print_arr_lambda.call([1,2,3])
is of type Array
, not Array[int]
. This script does seem to work:
@tool
extends EditorScript
func print_arr_func(a:Array[int]):
print(a)
func _run() -> void:
print_arr_func([1,2,3])
var print_arr_lambda = func(a : Array[int]): print(a)
var arr : Array[int] = [1,2,3]
print_arr_lambda.call(arr)
var print_arr_func_lambda = print_arr_func
print_arr_func_lambda.call(arr)
1 Like
array of [1,2,3] is untyped, regardless if it has values of same type. If you still need to pass int args, consider use PackedInt32Array([1,2,3])
Okay, so PackedInt32Array([1,2,3]) works for lambdas, even if it’s verbose. Thank you.
But why then does the untyped Array arg work for the native function print_arr_func
but not the lambda versions?
FYI, print_arr_func(["a","b","c"])
produces the error:
Parse Error: Cannot have an element of type "String" in an array of type "Array[int]".
which is what I would expect if indeed it was parsing the parameter as a fully-typed Array[int].
It seems like in some circumstances (e.g. involving Callables), Array will not be coerced into Array[int]. But in a regular function call it will be. As pointed out above, there does seem to be existing discussion about this.
1 Like
Try
print_arr_lambda.call([1,2,3] as Array[int])
The problem is gdscript has no typing for arrays when they are just constant literals. So it defaulta to untyped Array when there is no hint. You can cast them still.
1 Like