Topic was automatically imported from the old Question2Answer platform.
Asked By
Newbie
Old Version
Published before Godot 3 was released.
I have some arrays stored outside of main script
arrays.gd
var 1A = ["first taskA", "second taskA"]
var 1B = ["first taskB", "second taskB"]
var 2A = ["2.phase first taskA", "2.phase second taskA"]
var 2B = ["2.phase first taskB", "2.phase second taskB"]
and some variables according to which i want to select task
var source = "arrays" #I plan to be able to select various languages or difficulty
var phase = "1" #Changing while going throw level
var player = "B" #Which player is on turn
var random = randomly generated integer
select=("%s.%s%s[%s]" % [source, phase, player, random])
print(select) #output "arrays.1B[2]" but i want same like below
print(arrays.1B[2]) #output "second taskB"
I start scripting in python where i used function eval().
Is there some method how to use placeholders for variables? Or change string to variable call?
GDScript doesn’t allow variables names to start with a number. I suggest you prefix them or use a dictionary.
There is a way to access GDScript class members if you have their name as a string, with get and set.
Assuming arrays is an instance of your script or a an auto-load global and you prefix them with array_ (just as example):
var current = arrays.get("array_" + str(phase) + player)[random]
Thanks, that helps me a lot.
Expand of previous question. [EDIT:Solved]
How to change source script arrays in same manner as get arguments?
something like these:
var source = arrays #source can by changed by any function ...
var current = source.get("array_" + str(phase) + player)[rand]
I would recommend using a Dictionary for this instead, if you want to concatenate strings together as a key. (Correction: As pointed out by Zylann, you can start dictionary keys with numbers if you set the keys using strings. IE: dictionary[“1st Key”])
So something like:
var data = {
phase1A = ["first taskA", "second taskA"],
phase1B = ["first taskB", "second taskB"],
phase2A = ["2.phase first taskA", "2.phase second taskA"],
phase2B = ["2.phase first taskB", "2.phase second taskB"]
}
func get_data(phase_number, task_letter):
return data["phase" + str(phase_number) + task_letter]
func _ready():
for i in range(1, 3):
print(get_data(i, "A"))
print(get_data(i, "B"))
The other options would be writing your own data structures using a class, or making a special parsing function.
Are you sure dictionary keys can’t start with a number? That would be pretty lame. You can probably not access those with the dict.the_key syntactic sugar, but you definitely can by using the generic syntax dict["1234guidkey"].
Zylann | 2017-02-01 19:58
Didn’t try it until now, hadn’t considered that the string keys would allow it.