cak3_lover
cak3_lover

Reputation: 1958

How to convert data type if Variant.Type is known?

How do I convert the data type if I know the Variant.Type from typeof()?

for example:

var a=5;
var b=6.9;
type_cast(b,typeof(a)); # this makes b an int type value

Upvotes: 0

Views: 3790

Answers (1)

Theraot
Theraot

Reputation: 40315

How do I convert the data type if I know the Variant.Type from typeof()?

You can't. GDScript does not have generics/type templates, so beyond simple type inference, there is no way to specify a type without knowing the type.

Thus, any workaround to cast the value to a type only known at runtime would have to be declared to return Variant, because there is no way to specify the type.

Furthermore, to store the result on a variable, how do you declare the variable if you don't know the type?


Let us have a look at variable declarations. If you do not specify a type, you get a Variant.

For example in this code, a is a Variant that happens to have an int value:

var a = 5

In this other example a is an int:

var a:int = 5

This is also an int:

var a := 5

In this case the variable is typed according to what you are using to initialized, that is the type is inferred.

You may think you can use that like this:

var a = 5
var b := a

Well, no. That is an error. "The variable type can't be inferred". As far as Godot is concerned a does not have a type in this example.


I'm storing data in a json file: { variable:[ typeof(variable), variable_value ] } I added typeof() because for example I store an int but when I reassign it from the file it gets converted to float (one of many other examples)

It is true that JSON is not good at storing Godot types. Which is why many authors do not recommend using JSON to save state.

Now, be aware that we can't get a variable with the right type as explained above. Instead we should try to get a Variant of the right type.

If you cannot change the serialization format, then you are going to need one big match statement. Something like this:

match type:
    TYPE_NIL:
        return null
    TYPE_BOOL:
        return bool(value)
    TYPE_INT:
        return int(value)
    TYPE_REAL:
        return float(value)
    TYPE_STRING:
        return str(value)

Those are not all the types that a Variant can hold, but I think it would do for JSON.


Now, if you can change the serialization format, then I will suggest to use str2var and var2str.

For example:

var2str(Vector2(1, 10))

Will return a String value "Vector2( 1, 10 )". And if you do:

str2var("Vector2( 1, 10 )")

You get a Variant with a Vector2 with 1 for the x, and 10 for the y.

This way you can always store Strings, in a human readable format, that Godot can parse. And if you want to do that for whole objects, or you want to put them in a JSON structure, that is up to you.

By the way, you might also be interested in ResourceFormatSaver and ResourceFormatLoader.

Upvotes: 2

Related Questions