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

@@ -0,0 +1,13 @@
@static_unload
static var foo = "bar"
static func _static_init():
print("static init called")
prints("foo is", foo)
func test():
var _lambda = func _static_init():
print("lambda does not conflict with static constructor")
print("done")

View File

@@ -0,0 +1,4 @@
GDTEST_OK
static init called
foo is bar
done

View File

@@ -0,0 +1,56 @@
@static_unload
static var perm := 0
static var prop := "Hello!":
get: return prop + " suffix"
set(value): prop = "prefix " + str(value)
static func get_data():
return "data"
static var data = get_data()
class Inner:
static var prop := "inner"
static func _static_init() -> void:
prints("Inner._static_init", prop)
class InnerInner:
static var prop := "inner inner"
static func _static_init() -> void:
prints("InnerInner._static_init", prop)
func test():
prints("data:", data)
prints("perm:", perm)
prints("prop:", prop)
perm = 1
prop = "World!"
prints("perm:", perm)
prints("prop:", prop)
print("other.perm:", StaticVariablesOther.perm)
print("other.prop:", StaticVariablesOther.prop)
StaticVariablesOther.perm = 2
StaticVariablesOther.prop = "foo"
print("other.perm:", StaticVariablesOther.perm)
print("other.prop:", StaticVariablesOther.prop)
@warning_ignore("unsafe_method_access")
var path = get_script().get_path().get_base_dir()
var other = load(path + "/static_variables_load.gd")
print("load.perm:", other.perm)
print("load.prop:", other.prop)
other.perm = 3
other.prop = "bar"
print("load.perm:", other.perm)
print("load.prop:", other.prop)

View File

@@ -0,0 +1,16 @@
GDTEST_OK
Inner._static_init inner
InnerInner._static_init inner inner
data: data
perm: 0
prop: prefix Hello! suffix
perm: 1
prop: prefix World! suffix
other.perm:0
other.prop:prefix Hello! suffix
other.perm:2
other.prop:prefix foo suffix
load.perm:0
load.prop:prefix Hello! suffix
load.perm:3
load.prop:prefix bar suffix

View File

@@ -0,0 +1,10 @@
@static_unload
static var perm := 0
static var prop := "Hello!":
get: return prop + " suffix"
set(value): prop = "prefix " + str(value)
func test():
print("ok")

View File

@@ -0,0 +1,2 @@
GDTEST_OK
ok

View File

@@ -0,0 +1,11 @@
@static_unload
class_name StaticVariablesOther
static var perm := 0
static var prop := "Hello!":
get: return prop + " suffix"
set(value): prop = "prefix " + str(value)
func test():
print("ok")

View File

@@ -0,0 +1,2 @@
GDTEST_OK
ok