Quantcast
Channel: mel wiki
Viewing all articles
Browse latest Browse all 610

How can I convert from string to int?

$
0
0
Some languages give you the ability to Boolean test strings: You can convert a string to a Boolean, and if the string has any characters, the bool = True. If the string is empty, the bool = False. How to do something similar with mel?

Mel doesn't have Boolean variable types, so we have to fake it with an int. (Although, you can make Boolean attribute types. Odd you can make one but not the other.)

You could try this, but we get a warning, and an int of 0:
string $s = "word";
int $i = $s;
// Warning: line 2: Converting string "word" to an int value of 0. // 
// Result: 0 // 
However, you could use the '?' operator, and get the result you're after:
string $s = "word";
int $i = size($s) ? 1 : 0;
// Result: 1 // 
Show help docs on the ? operator:
showHelp -d "General/_operator.html";


Similar stuff in Python. Python does have Boolean object types, so we first convert the string to Boolean, then to int (or obviously leave off the int part if all you want is the bool). Trying to convert a string directly to an int raises a ValueError.
s = "word"
i = int(bool(s))
# 1

Viewing all articles
Browse latest Browse all 610

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>