How do I convert a String to a GDScript value?

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

I’ll load a .ini file that contains Color values. For example:

DarkColor=Color(0.2, 0.2, 0.2)

This declaration is in the .ini file and I need to load and convert this but I don’t know how.

:bust_in_silhouette: Reply From: SIsilicon

Now be sure to read the comments in this code. They’re important.

# First, you access the file for reading like so.
var file = File.new()
file.open("path/to/file.ini", file.READ)

var colours = {}

# Then you read each line sequentially.
while not file.eof_reached()
    var line = file.get_line()
    line = line.get_replace(" ", "") # remove any spaces

    # get the name of the colour
    var col_name = line.substr(0, line.find("="))

    var colour = Color()
    var val_start = line.find("Color(") + 6
    var val_end = 0

    # Read each colour component into the colour variable
    for i in 3:
        val_end = line.find(",", val_end + 1)
        var component = line.substr(val_start, val_end-val_start if val_end !=  -1 else len(line)-val_start-1)
        val_start = val_end +1

        match i:
            0: colour.r = float(component)
            1: colour.g = float(component)
            2: colour.b = float(component)
    # We put the colour into the dictionary
    colours[col_name] = colour

# Since we're done with the file, we should close it.
file.close()

It could work very well. Thanks.

JulioYagami | 2018-12-19 23:38