|
|
|
Type ConversionsValues of one type can be converted to a value of another type. For example, the integer 4711 can be converted to the string "4711". (These two may look similar, but they are actually entirely different things. For example, 4711 + 3 will give you 4714, "4711" + "3" will give you "47113".) Some conversions are done automatically. For example, in the expression "hello" + 17 the integer 17 will be automatically converted to the string "17", before the two strings are concatenated, giving the result "hello17". But some conversions need to be performed with a special operation, called an explicit type conversion or cast. There is a special cast operator, which is written as a data type between parentheses: (float)14 // Gives the float 14.0 (int)6.9 // Gives the int 6 (string)6.7 // Gives the string "6.7" (float)"6.7" // Gives the float 6.7 Here is a list of some useful casts:
Sometimes you know more than what Pike does about data types, and another use of the cast operator is to tell Pike what you know. For example, lets say that you have a variable with the type mixed, which means that it can contain any type of data. Lets also say that you happen to know that that variable contains an integer. If you want to use this value where an integer is required, Pike might complain about it: mixed m; int i; m = 18; i = m; // This might make Pike suspicious You can use a cast to tell Pike that m is an integer and nothing else: i = (int)m; // Don't worry. I promise it's an int! |
||||||||||||||||||||||||||||||||||||