Add support for static variables in GDScript

Which allows editable data associated with a particular class instead of
the instance. Scripts with static variables are kept in memory
indefinitely unless the `@static_unload` annotation is used or the
`static_unload()` method is called on the GDScript.

If the custom function `_static_init()` exists it will be called when
the class is loaded, after the static variables are set.
This commit is contained in:
George Marques
2023-04-19 11:10:35 -03:00
parent 352ebe9725
commit 0ba6048ad3
36 changed files with 689 additions and 86 deletions

View File

@ -94,6 +94,8 @@ class GDScript : public Script {
HashSet<StringName> members; //members are just indices to the instantiated script.
HashMap<StringName, Variant> constants;
HashMap<StringName, MemberInfo> static_variables_indices;
Vector<Variant> static_variables;
HashMap<StringName, GDScriptFunction *> member_functions;
HashMap<StringName, MemberInfo> member_indices; //members are just indices to the instantiated script.
HashMap<StringName, Ref<GDScript>> subclasses;
@ -102,6 +104,12 @@ class GDScript : public Script {
#ifdef TOOLS_ENABLED
// For static data storage during hot-reloading.
HashMap<StringName, MemberInfo> old_static_variables_indices;
Vector<Variant> old_static_variables;
void _save_old_static_data();
void _restore_old_static_data();
HashMap<StringName, int> member_lines;
HashMap<StringName, Variant> member_default_values;
List<PropertyInfo> members_cache;
@ -123,6 +131,9 @@ class GDScript : public Script {
GDScriptFunction *implicit_initializer = nullptr;
GDScriptFunction *initializer = nullptr; //direct pointer to new , faster to locate
GDScriptFunction *implicit_ready = nullptr;
GDScriptFunction *static_initializer = nullptr;
Error _static_init();
int subclass_count = 0;
RBSet<Object *> instances;
@ -268,6 +279,8 @@ public:
virtual const Variant get_rpc_config() const override;
void unload_static() const;
#ifdef TOOLS_ENABLED
virtual bool is_placeholder_fallback_enabled() const override { return placeholder_fallback_enabled; }
#endif
@ -439,6 +452,7 @@ public:
struct {
StringName _init;
StringName _static_init;
StringName _notification;
StringName _set;
StringName _get;