pythonrenpy

How to modify multiple global variables in a python function


I have several variables and want to modify them with a single function.

default strength = 0
default dex = 0
default wis = 0
default cha = 0
default point_pool = 5   

I can do something like:

def inc_strength():
    global strength
    global point_pool

    if strength<5 and point_pool>0:
        strength = strength+1
        point_pool = point_pool-1

But I don't want to create one for each stat. I'd prefer to pass the variable I want to use a param, but am struggling. Something like:

def stat_inc(stat):
    global point_pool

    if stat<5 and point_pool>0:
        stat = stat+1
        point_pool = point_pool-1

And call it with:

 action Function(stat_inc(strength))

Solution

  • You can directly update the globals() dictionary:

    >>> def stat_inc(arg1, arg2):
        stat = globals()[arg1]
        point_pool = globals()[arg2]
    
        if stat<5 and point_pool>0:
            stat = stat+1
            point_pool = point_pool-1
        globals()[arg1] = stat
        globals()[arg2] = point_pool
    
    >>> stat=3
    >>> point_pool = 3
    >>> stat_inc('stat', 'point_pool')
    >>> stat, point_pool
    (4, 2)
    

    That said, I think modifying global values is rarely needed, so it is better if you can do without it.