Skip to content

Add support for initializer_list to Array and TypedArray #1716

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

Merged
merged 1 commit into from
Apr 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion binding_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,7 @@ def generate_builtin_class_header(builtin_api, size, used_classes, fully_used_cl
result.append("#include <godot_cpp/variant/vector4.hpp>")
result.append("")

if is_packed_array(class_name):
if is_packed_array(class_name) or class_name == "Array":
result.append("#include <godot_cpp/core/error_macros.hpp>")
result.append("#include <initializer_list>")
result.append("")
Expand Down Expand Up @@ -953,6 +953,7 @@ def generate_builtin_class_header(builtin_api, size, used_classes, fully_used_cl
_FORCE_INLINE_ ConstIterator begin() const;
_FORCE_INLINE_ ConstIterator end() const;
""")
result.append("\t_FORCE_INLINE_ Array(std::initializer_list<Variant> p_init);")

if class_name == "Dictionary":
result.append("\tconst Variant &operator[](const Variant &p_key) const;")
Expand Down
5 changes: 5 additions & 0 deletions include/godot_cpp/variant/typed_array.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ class TypedArray : public Array {
assign(p_array);
}
}
_FORCE_INLINE_ TypedArray(std::initializer_list<Variant> p_init) :
TypedArray(Array(p_init)) {}
_FORCE_INLINE_ TypedArray() {
set_typed(Variant::OBJECT, T::get_class_static(), Variant());
}
Expand All @@ -68,6 +70,9 @@ class TypedArray : public Array {
ERR_FAIL_COND_MSG(!is_same_typed(p_array), "Cannot assign an array with a different element type."); \
_ref(p_array); \
} \
_FORCE_INLINE_ TypedArray(std::initializer_list<Variant> p_init) : \
Array(Array(p_init), m_variant_type, StringName(), Variant()) { \
} \
_FORCE_INLINE_ TypedArray(const Variant &p_variant) : \
TypedArray(Array(p_variant)) { \
} \
Expand Down
9 changes: 9 additions & 0 deletions include/godot_cpp/variant/variant.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,15 @@ Array::ConstIterator Array::end() const {
return Array::ConstIterator(ptr() + size());
}

Array::Array(std::initializer_list<Variant> p_init) {
ERR_FAIL_COND(resize(p_init.size()) != 0);

size_t i = 0;
for (const Variant &element : p_init) {
set(i++, element);
}
}

#include <godot_cpp/variant/builtin_vararg_methods.hpp>

#ifdef REAL_T_IS_DOUBLE
Expand Down