godot: str2var crashes the application when processing a non-convertible string - not very useful behavior
A common use case for str2var for me is to have it go through a collection of string variables and have it convert them to the appropriate type. This however becomes a problem, as str2var will crash godot if it encounters a variable that is supposed to be a string in the first place.
I think it would be more useful if the function simply returns the original input string in that case, rather than crashing the engine.
I made an ugly workaround function to get around that- just to stop it from crashing:
func cusStr2Var(inputString):
if !isItAString(inputString):
return str2var(inputString)
else: return inputString
func isItAString(string): ##fixed
var NameRegEx = RegEx.new()
NameRegEx.compile('[A-Za-z]+')
if NameRegEx.search(string) != null:
return true
else: return false
Its messy, might have to rewrite it, the idea is to avoid crashing
But would really like it if I didn’t have to 😃 If you want to keep the crash message as to why it failed to convert it, why not turn it into a warning instead?
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 15 (10 by maintainers)
Actually, returning the original string sounds like the best solution. You can compare the input and the output and if they’re the same it means the parsing failed.
No, I think it should be changed only for GDScript (since this is a GDScript-only function), so just change this if block to just return the original argument instead of creating an error:
https://github.com/godotengine/godot/blob/1fa9aac3e415f53a095e955c8a37000629d56dde/modules/gdscript/gdscript_functions.cpp#L702-L708
People using the VariantParser directly can detect the error themselves.
I’m not necessarily opposed to changing things to prevent a crash, but I don’t think a second parameter is the answer in this case. A more efficient solution might be to have it return an ERR_* integer in case of failure. Doesn’t seem as though it would be that difficult to implement. Granted, I don’t know how it’s string parsing works or whether it can be evaluated in advance, prior to the crash check.
For one side it’s good to have it error, since it can avoid bugs. OTOH this current behavior makes it impossible to recovery, since Godot offers no error handling.
I don’t like returning the original string, it makes impossible to know if it was a success or not. TBH this is also the case for
null
, it’s totally possible to the original value was aNull
sincetypeof(str2var('null')) == TYPE_NIL
istrue
.Also note that for a string to parsed correctly, it needs to be enclosed in double-quotes:
print(str2var('"This will print nicely"'))
.