How to get and set a non-object variant property by name in gdscript

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By gnumaru

Is there a built-in way to get and set a non-object variant property by its name?

The Object class have the get and set methods which can do just that, but other variant types (like Vector2 or Color) does not.

Currently I’m using a helper method defined in an autoload in order to do this. It works fine, but It would be better to not resort to workarounds, specially for setting, since all variants except object, dictionary and array are passed by value and thus you cannot directly change a property that was passed as a function parameter, you have to return the modified variant and assign the value back in the caller for it to work.

Bellow are my current helper functions.

# this goes inside an autoloaded class named 'U' ('U' stands for Utilities and is quick to type)
var var_get_set_tmp # this temporary property is needed to use get_indexed and set_indexed.

static func var_get(target, property:String):
    if target is Object:
        if not is_instance_valid(target):
            return
        return target.get(property)

    U.var_get_set_tmp = target
    var out = U.get_indexed('var_get_set_tmp:%s'%property)
    U.var_get_set_tmp = null
    return out

static func var_set(target, property:String, value):
    if target is Object:
        if not is_instance_valid(target):
            return
        target.set(property, value)
        return target

    U.var_get_set_tmp = target
    U.set_indexed('var_get_set_tmp:%s'%property, value)
    target = U.var_get_set_tmp
    U.var_get_set_tmp = null
    return target