Skip to content

Commit

Permalink
Use regex for cast to int validation.
Browse files Browse the repository at this point in the history
  • Loading branch information
DylanCheetah committed Nov 23, 2024
1 parent 09bcee5 commit 4f28ca0
Showing 1 changed file with 6 additions and 15 deletions.
21 changes: 6 additions & 15 deletions core/variant.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@
#include "core/variant_parser.h"
#include "scene/gui/control.h"
#include "scene/main/node.h"
#include "modules/regex/regex.h"

RegEx number("^((-?\\d+)(\\.\\d+)?|true|false)$");

String Variant::get_type_name(Variant::Type p_type) {
switch (p_type) {
Expand Down Expand Up @@ -605,21 +608,9 @@ bool Variant::can_convert(Type p_type_to) const {
// If this is a string variant and we are converting to an integer, check if the contents of the string
// make sense as an integer
if (type == Type::STRING && p_type_to == Type::INT) {
// Get a reference to the string
String s = operator String();

// Is the first character a numeral?
if (s.length() > 0 && s[0] >= '0' && s[0] <= '9') {
return true;
}

// Is the first character '-' and the second character a numeral?
if (s.length() > 1 && s[0] == '-' && s[1] >= '0' && s[1] <= '9') {
return true;
}

// The string cannot be converted to a valid integer
return false;
// Use regular expression to validate the string
Ref<RegExMatch> match = number.search(operator String());
return match != NULL;
}

// Do other type checks
Expand Down

0 comments on commit 4f28ca0

Please sign in to comment.