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: Initialize static variables with defaults in-editor #91472

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
24 changes: 24 additions & 0 deletions modules/gdscript/gdscript.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,27 @@ Error GDScript::_static_init() {

#ifdef TOOLS_ENABLED

void GDScript::_static_default_init() {
for (const KeyValue<StringName, MemberInfo> &E : static_variables_indices) {
const GDScriptDataType &type = E.value.data_type;
// Only initialize builtin types, which are not expected to be `null`.
if (!type.has_type || type.kind != GDScriptDataType::BUILTIN) {
continue;
}
if (type.builtin_type == Variant::ARRAY && type.has_container_element_type(0)) {
Array default_value;
const GDScriptDataType &element_type = type.get_container_element_type(0);
default_value.set_typed(element_type.builtin_type, element_type.native_type, element_type.script_type);
static_variables.write[E.value.index] = default_value;
} else {
Variant default_value;
Callable::CallError err;
Variant::construct(type.builtin_type, default_value, nullptr, 0, err);
static_variables.write[E.value.index] = default_value;
}
}
}

void GDScript::_save_old_static_data() {
old_static_variables_indices = static_variables_indices;
old_static_variables = static_variables;
Expand Down Expand Up @@ -841,6 +862,9 @@ Error GDScript::reload(bool p_keep_state) {
#ifdef TOOLS_ENABLED
if (can_run && p_keep_state) {
_restore_old_static_data();
} else if (!can_run) {
// Initialize static variables with sane default values even if the constructor isn't called.
_static_default_init();
}
#endif

Expand Down
3 changes: 3 additions & 0 deletions modules/gdscript/gdscript.h
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,9 @@ class GDScript : public Script {
GDScriptFunction *static_initializer = nullptr;

Error _static_init();
#ifdef TOOLS_ENABLED
void _static_default_init(); // Initialize static variables with default values based on their types.
#endif

int subclass_count = 0;
RBSet<Object *> instances;
Expand Down
Loading