1

Is there a syntax to cast from one character type for another? For example can you cast from a char to an int?

I tried:

let my_var = (int)some_char

It is not valid code.

11
  • 4
    It helps reading Vim's scripting help first ... To quote: Vim automatically converts a string to a number when it is looking for a number. If you want ASCII char conversion instead, see char2nr() and nr2char().
    – VanLaser
    Mar 6, 2016 at 15:07
  • 2
    And there's the str2nr function.
    – muru
    Mar 6, 2016 at 15:18
  • 2
    If you know it is a number, you can also simply add zero to it. Mar 6, 2016 at 15:19
  • 2
    learnvimscriptthehardway.stevelosh.com (sections: "variables", "numbers" and "strings")
    – VanLaser
    Mar 6, 2016 at 15:41
  • 2
    :help variables Mar 6, 2016 at 15:42

2 Answers 2

2

The answer is no. There is no general syntax to cast from one type to another. There are unique ways of converting to different types, but no universal casting syntax.

0

You can do this in a round about way by first casting the float to a string then casting it to number for example:

echom str2nr(string(log10(200)))

Hope this helps people searching in the future.

1
  • Welcome to Vi and Vim! You haven't quite answered the question, which asked about character types (char and int), but thanks for sharing the knowledge!
    – D. Ben Knoble
    Jan 9, 2020 at 5:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.