system
1
|
|
|
 |
Attention |
Topic was automatically imported from the old Question2Answer platform. |
 |
Asked By |
cheo |
Is it possible to dinamycally create variables by using array elements or dictionary keys as variable names?
For instance:
var demo = ["var1","var2"]
func _ready():
set(demo[0], "Hi")
print(get(demo[0]))
I’m expecting to see “Hi” in the console, but I get a Null
system
2
|
|
|
 |
Reply From: |
Zylann |
No, it doesn’t work this way. Variables made with var
or accessed with get
and set
have to be declared somewhere first:
var demo = ["var1","var2"]
# Declaring
var var1
var var2
var demo = ["var1","var2"]
func _ready():
set(demo[0], "Hi")
print(get(demo[0]))
If you want dynamic vars created at runtime, you can use a dictionary:
var demo = ["var1","var2"]
var vars = {}
func _ready():
vars[demo[0]] = "Hi"
print(vars[demo[0]])
If you are reaaaaally desperate to use get
and set
for some reason, you can override _get
and _set
:
var demo = ["var1","var2"]
var vars = {}
func _ready():
set(demo[0]) = "Hi"
print(get(demo[0]))
func _get(key):
return vars[key]
func _set(key, value):
vars[key] = value