ID:1674908
 
(See the best response by Kaiochao.)
Just for practice, I'm trying to make a verb that will take as input from the usr a string, and spit back out a new string consisting only of the numbers that were in the original string.

Here's what I'm trying...

mob/verb
only_numbers()
var/new_string = ""
var/x = input("Enter some text:")
for(var/character in x)
if(isnum(character))
new_string += character
usr << "[new_string]"


This only produces a blank line. Is it because that all characters that are entered into "input" are all "text" and not "num"s?

I even tried doing something like this...

read_backer()
var/message = input("Enter a string: ")
for(var/character in message)
usr << "[character]"


This also produces just a blank line. I expected it to print out every character supplied in the message var on its own, separate line.

I feel like something like this would work in Python, but I can't quite get it using DM. For() seems to work differently.

Any help would be appreciated.
Best response
You can't loop through characters in a string using for-in.

A straightforward alternative would be to use ascii2text(text2ascii(string, n)), which gets the nth character in the string (with 1 being the first).

isnum(x) checks if x is a numeric value, which strings (including "123") are not, so isnum() isn't suitable for this exercise. Instead, you should use text2num(x), which returns null if x (a string) doesn't start with a number.

The answer in this case, if you want it:
proc/filter_numbers(string)
// we want the return value to be a string
. = ""

// loop for n = 1 to n = length of the string
for(var/n in 1 to length(string))

// get the nth character in the string
var char = ascii2text(text2ascii(string, n))

// concatenate the number to ., a string
. += text2num(char)
As always, Kaiochao, thanks!
As this is practice, I feel I should mention you can extend this to character filtering by applying based on the ascii code instead, removing the need for text2num.

http://www.asciitable.com/

proc/filter_numbers(string)
// we want the return value to be a string
. = ""

// loop for n = 1 to n = length of the string
for(var/n in 1 to length(string))
// get the nth character in the string
var ascii = text2ascii(string, n)
if(ascii in 48 to 57) .+= ascii2text(ascii)