Skip to content

Instantly share code, notes, and snippets.

@kana
Created October 6, 2021 23:08
Show Gist options
  • Save kana/fc741c64a01c515a7cf73f6958128d26 to your computer and use it in GitHub Desktop.
Save kana/fc741c64a01c515a7cf73f6958128d26 to your computer and use it in GitHub Desktop.
"A is B" in Vim9 script
vim9script
# "A is 0" in legacy Vim script is an idiom to compare values which might be
# different types. This is especially useful to check the existence of a key
# in a dictionary and to use its value if that key exists. For example:
#
# let Hook = get(g:config, 'hook', 0)
# if Hook is 0
# return
# endif
# call Hook('...')
#
# In Vim9 script, it's a compile error if both operands are known as non-any
# types at the compile time.
function InLegacyScript(a, b)
return a:a is a:b
endfunction
def InVim9Script(a: any, b: any): bool
return a is b
enddef
echo InLegacyScript(0, 0)
#==> 1
echo InLegacyScript('0', 0)
#==> 0
echo InLegacyScript([], 0)
#==> 0
echo InLegacyScript({}, 0)
#==> 0
echo InVim9Script(0, 0)
#==> true
echo InVim9Script('0', 0)
#==> false
echo InVim9Script([], 0)
#==> false
echo InVim9Script({}, 0)
#==> false
def Safe(): bool
const a: any = '0'
return a is 0
enddef
echo Safe()
#==> false
def CompileError(): bool
const a = '0'
return a is 0
enddef
echo CompileError()
# Error detected while compiling command line..[...]..function <SNR>1_CompileError:
# line 2:
# E1072: Cannot compare string with number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment