Game Development Community

Simple scripting question

by Revisionary · in Torque Game Builder · 11/07/2009 (8:48 am) · 4 replies

Is there a function which can extract a single digit from an integer? ie: the "2" from "10092"? I would use getSubStr, but I can not figure out how to convert an int to a string. I searched the forums, am I the only person who wants to do this? Or is it something so obvious that I should already know?

#1
11/07/2009 (9:07 am)
If you are looking for only the last single digit, % with 10 might be easier.

%val = 10092 % 10;
  error(%val); // 2
#2
11/07/2009 (9:20 am)
Aun is right, although looks like he mistyped the divisor :)

%val = 10092 % 10090;
echo(%val);

'%' is the function modulo, widely used to make what you need, Rev.

See here for more info.
#3
11/08/2009 (4:06 am)
Actually, Aun is correct. This is a trivial operation that a lot of game programmers pick up over the years.

In C++, you might do the following to get the digits:
// This code won't work just right when val = 0,
// but this is for example purposes only.
int val = 10092;
while( val > 0 )
{
  int endDigit = val % 10;
  // Do something with endDigit (store it, display it, whatever)
  val /= 10;
}

But people tend to forget that all literals in TorqueScript are strings. You should take advantage of that:
$val = 10092; 
$len = strlen( $val ); 
for( %i = 0; %i < $len; %i++ )
  echo( getSubStr( $val, %i, 1 ) );

You can put this all on one line in the console:
$val = 10092; $len = strlen( $val ); for( %i = 0; %i < $len; %i++ ) echo( getSubStr( $val, %i, 1 ) );
and see that it results in
1
0
0
9
2
#4
11/08/2009 (7:52 am)
Thanks all, that helped a ton. I must have had a syntax problem with getSubStr the first time I tried - it works like a charm now.