0 votes

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?

Godot version 3.2.3
in Engine by (80 points)

2 Answers

–1 vote

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 = ""
by (2,394 points)
+1 vote

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.
by (12,286 points)
edited by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.