Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GDScript 2.0: Type casting (as) not working with typed arrays #54311

Open
Scony opened this issue Oct 27, 2021 · 2 comments
Open

GDScript 2.0: Type casting (as) not working with typed arrays #54311

Scony opened this issue Oct 27, 2021 · 2 comments

Comments

@Scony
Copy link
Contributor

Scony commented Oct 27, 2021

Godot version

4.0.dev.custom_build.3bebbcacd

System information

manjaro linux

Issue description

print([1,2.1] as Array[int])

yields

[1, 2.1]

while it should cast elements to int I believe.

Steps to reproduce

Run the above.

Minimal reproduction project

No response

@KoBeWi KoBeWi added this to the 4.0 milestone Oct 27, 2021
@Calinou Calinou changed the title type casting not working with typed arrays GDScript 2.0: Type casting (as) not working with typed arrays Oct 27, 2021
@YuriSizov YuriSizov modified the milestones: 4.0, 4.1 Feb 27, 2023
@dalexeev
Copy link
Member

dalexeev commented Jun 14, 2023

In 4.0.3 this works for constants and literals, but the bug remains for variables. In fact, the as operator only works correctly with objects, it has always worked inconsistently with Variant types (raises a runtime error instead of returning a default value), we should probably change this behavior.

print(var_to_str([1, 2.1] as Array[int])) # Array[int]([1, 2])
var x = [1, 2.1]
print(var_to_str(x as Array[int])) # [1, 2.1]
var y: Array[float] = [1, 2.1]
print(var_to_str(x as Array[int])) # [1, 2.1]

Also note the difference between casting and conversion, as should not convert an array at runtime and creating a new one (except if no conversion is possible), it should allow the static analyzer to change the type interpretation. For conversion, there is Array.assign() method and there is PR #71336 for a typed constructor.

@YuriSizov YuriSizov modified the milestones: 4.1, 4.2 Jun 26, 2023
@dalexeev
Copy link
Member

We have not resolved all the design issues of typed arrays, but I don’t think that type casting should not create new data, only change the static type of the expression (when casting to a supertype) and provide a safe value in case of a type mismatch at runtime (when casting to a subtype). However, we introduced this behavior for array literals.

In any case, we cannot move forward until a consensus is found in the discussion. It would be nice to document the current implementation, but I don't think it's urgent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants