Adabelitoo wrote: ↑Wed May 08, 2024 5:35 pm
I was looking for that and I found this post with the same question, but I didn't understand exactly how that works.
When you create a variable in Renpy script language using the keyword "default", Renpy will then create an attribute of that name inside its "store" object.
So for example if you do this:
then this variable is also available via
store.rp_linda.
Now in Python there is a method to access attributes of objects via their name (as a string) using the "getattr" and "setattr" functions. So as an example:
Code: Select all
# two ways of changing the variables contents inside of the store:
# this is the normal way, but we cannot use the name dynamically
$ store.rp_linda = 1
# here we just pass the variable name as a string, which is handy
$ setattr(store, "rp_linda", 1)
# and this is how we could read it using a string
$ current_value = getattr(store, "rp_linda")
So since this setup uses strings, it allows us to dynamically change variable names when reading or writing them. Here is your example code using this technique:
Code: Select all
label 1in4chance:
$ num_random = renpy.random.randint(1, 4)
if num_random == 4:
pass
else:
# the idea: $ rp_[cha_name] -= 1
# let's just use three lines of code to make it clear
$ variable_name = f"rp_{cha_name}"
$ current_value = getattr(store, variable_name)
$ setattr(store, variable_name, current_value - 1)
return
But to be honest, if you just have 4 variables, you could also use conditions, right... readable code is better than fancy looking one. It probably takes the CPU less time to execute simple if-else statements as well.
Code: Select all
if cha_name == "linda":
$ rp_linda -= 1
elif cha_name == "bob":
$ rp_bob -= 1
# etc.