Let's see if I understand: you want to use the content of the incoming
parameter to select the variable to print, but without explicitly checking it (ie: if incoming == "alive": print(alive) elif incoming == "dead" ...
), right? You can use index notation to access a variable's content with a string, like this:
var myVar = "Hello world"
func _ready():
var stringToPrint = self["myVar"]
print(stringToPrint)
Your script 2 would end up like this:
var alive = "I live!"
var dead = "I'm not alive!"
func _testing_for(incoming):
print(self[incoming])
However, if you feel the need to access different variables by string, it usually indicates that what you want is a dictionary. Here's what that would look like:
var states= {
"alive": "I live!",
"dead": "I'm not alive!"
}
func _testing_for(incoming):
print(states[incoming])
You can add a check to see if the key exists in the dictionary before accessing it (if states.has(incoming): ...
), since accessing a value that doesn't exist will throw an exception, but sometimes you want the game to crash immediately while developping so you can catch errors sooner (ex: the caller shouldn't call _testing_for
with a value that doesn't exist.
An improved version would use something like an enum for keys:
enum States {
alive,
dead
}
var states= {
States.alive: "I live!",
States.dead: "I'm not alive!"
}
func _testing_for(incoming): #incoming must be one of States enum
print(states[incoming])
You would call _testing_for
from another scripts like so:
func _set_parameters():
var outcome
if test = true:
outcome = $other_script.States.alive
else:
outcome = $other_script.States.dead
$other_script._testing_for(outcome)
Using an enum means you can more clearly define what values can be passed to your function and makes it less likely that you'll make typos in your strings.