Test if a conversion between data types happened successfully

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

How does one test if a conversion between data types happened succesfully without crashing the game?

Say there’s a TextEdit the user can write into. They’re supposed to write in an integer, however there is nothing physically preventing them from writing whatever else they want, like a string containing non-numerical characters. The optimal outcome is a popup window appearing, telling the user they cannot do that and deleting the invalid value in the faulty TextEdit, instead of the program stopping completely. But for that, a test must be carried out, I suppose. How does one do that?

:bust_in_silhouette: Reply From: Ertain

The input can be checked for primitive data types by using the typeof() function. Building on the integer example, the input can be checked like this:

if typeof(some_input) != TYPE_INT:
    popup_warning("Please type in an integer.") # Btw, this is not a built-in function.
    textEdit.text = ""
:bust_in_silhouette: Reply From: jgodfrey

For the specific example, attempting to convert (for instance) 123abc to an integer like below will result in 0 as the result.

var st = "123abc"
var result = int(st)
print(result) # prints "0"

So, it doesn’t really “fail” in the traditional sense, it just returns a (potentially) unexpected value when given invalid input. How you handle that is up to you, but could be any of:

  • Do nothing special - invalid input will result in a value of 0. That may or may not be OK for your use-case
  • Treat the resulting value of 0 as an error (show your popup). This would work if you don’t expect 0 as valid input.
  • You could “pre-scan” your string to ensure that it only contains digits prior to passing it to int(). That way, you’d be in complete control of any error handling (show your popup if the scan indicates invalid input). This would allow you to differentiate between a invalid input and an expected value of 0.