How do I check if a string contains only numbers?

MAXScript FAQ > MAXScript Values > How do I check if a string contains only numbers?

A user asked:

I want to check whether the text in an edit text UI element contains numbers or letters.

If it contains numbers, I want it to return the numbers. If it contains letters, I want it to display a message "You may only type numbers, try again".

How do I do that?

Answer:

SCRIPT

rollout MicroListener "MicroListener"
(
edittext myEditText text:""
label theLabel "Ready."
on myEditText changed txt do
(
 if txt != "" then
 (
  try
  (
   val = execute txt
   theLabel.text = "You typed in "+ (val as string )
  )
  catch 
   theLabel.text = "Invalid Expression!"
 )
 else
  theLabel.text = "Ready."
)
on myEditText entered txt do myEditText.text = ""
)
createDialog MicroListener 300 60

This simple script implements a kind of "micro-listener". It uses the Execute method to turn the string typed in the edit text field into a MAXScript expression. It lets you not only enter numbers, but also constants like Pi, or global variables that you have defined. Not only this, you can define global variables inside the script, and even create objects on the fly.

HERE ARE SOME EXAMPLES:

125.1 is a valid expression - it is a constant and evaluates to itself (125.1).

On the other hand, d returns undefined as it is undefined.

Surprisingly, e does not return undefined - it is a reserved keyword in MAXScript!

Same with pi -as expected, it returns 3.14149....

Trying to add two undefined values results in an invalid expression.

This variable is also undefined.

Until we define it. Now it is equal to 10.

So, you can write an expression containing constants and variables.

Typing in a function name, in this case the constructor of a box, you get the function back.

By calling the function, you can create objects just like in the "real" Listener.

This box is created 100 units to the right because the position is specified.

And, so on.

See Also