Skip to content

TypedArray argument is copied #1149

@pkdawson

Description

@pkdawson

Godot version

v4.1.beta2.mono.official [a2575cba4]

godot-cpp version

82edc89

System information

Windows 11 22H2

Issue description

If my method takes an Array parameter, it behaves as a reference to the original array which was passed in from GDScript, so it can be modified.

But if I change that to a TypedArray, the array is instead copied, and any changes are therefore lost.

void MyObject::AppendToArray(Array a)
{
    // works as expected
    a.append(100);
}

void MyObject::AppendToTypedArray(TypedArray<int> b)
{
    // original array is unchanged
    b.append(200);
}
var a = []
var b: Array[int] = []

MyObject.AppendToArray(a)
MyObject.AppendToTypedArray(b)

print(a) # [100]
print(b) # []

This is because the TypedArray constructors call a builtin Array constructor which makes a copy.

_FORCE_INLINE_ TypedArray(const Variant &p_variant) : \
Array(p_variant.operator Array(), m_variant_type, StringName(), Variant()) { \
} \
_FORCE_INLINE_ TypedArray(const Array &p_array) : \
Array(p_array, m_variant_type, StringName(), Variant()) { \
} \

https://github.com/godotengine/godot/blob/7b170d12cf0f8b3a15572fd203aa5cba840975f3/core/variant/array.cpp#L756-L761

If I change those base constructor calls to the single-argument Array constructor, it fixes the issue for me, but I'm not sure what the proper fix should be.

Steps to reproduce

Bind a method which takes a TypedArray parameter and modifies the array.

Minimal reproduction project

N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugThis has been identified as a bug

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions