Page 1 of 1

how to tell if a variable is integer?

Posted: 24 Sep 2018, 17:02
by wryyymuda
i need to see if a few of the variables in my code are integers and if they are not it just exits the program but i would rather have it state that that's the problem. any function or anything i can put in an if statement to test to see if it is an integer?

Re: how to tell if a variable is integer?

Posted: 24 Sep 2018, 17:20
by AHKStudent

Re: how to tell if a variable is integer?

Posted: 24 Sep 2018, 17:22
by wryyymuda
it always returns an error and exits the script saying whatever variable i put there is wrong.

Re: how to tell if a variable is integer?  Topic is solved

Posted: 24 Sep 2018, 17:24
by Exaskryz
If var is digit

Digit does not accept periods (nor commas), so it works in identifying a value as an integer. However, you may want to incorporate it with another check for it to have a value, as otherwise a null value in the variable is also accepted.

Code: Select all

If !var
{
MsgBox %var% has no value or is false
ExitApp
}
If var is not digit
{
MsgBox %var% is not an integer
ExitApp
}
Unfortunately you can't combine the If var is (not) [type] command with a traditional If expression. You could probably do this though; I haven't tested it:

Code: Select all

If !RegExMatch(var,"$\d+^)
{
MsgBox %var% is not an integer
ExitApp
}
The RegEx here searches for \d characters -- digits 0 through 9. The + means one or more digits must be found. The first matching character must be at the start of the entire haystack, per the $; the last matching character must be at the end of the entire haystack, per the ^ -- in other words, the entire string must be digits throughout.

Re: how to tell if a variable is integer?

Posted: 24 Sep 2018, 17:26
by wryyymuda
this is what i am doing

Code: Select all

if def is integer {
msgbox, test
rx = 1
exitapp
}

Re: how to tell if a variable is integer?

Posted: 24 Sep 2018, 17:27
by wryyymuda
it also says i can do
if var is not type
but that doesn't work

Re: how to tell if a variable is integer?

Posted: 24 Sep 2018, 17:40
by wryyymuda
nevermind you have to combine the is and not.

Re: how to tell if a variable is integer?

Posted: 25 Sep 2018, 03:37
by Rohwedder
Hallo,
try:

Code: Select all

def = 2.
if def is integer ;One True Brace style not allowed!
{
	MsgBox,,LineNumber: %A_LineNumber%, %def% is integer
}
if def is not integer ;One True Brace style not allowed!
{
	MsgBox,,LineNumber: %A_LineNumber%, %def% is not integer
}
If RegExMatch(def,"^\d+$") { ;One True Brace style allowed
	MsgBox,,LineNumber: %A_LineNumber%, %def% is integer
}
If !RegExMatch(def,"^\d+$") { ;One True Brace style allowed
	MsgBox,,LineNumber: %A_LineNumber%, %def% is not integer
}