'How to access script-variable in mapping?

I want to do following behaviour

let s:cmd = “echo ‘here is a long command’”

map aa :execute s:cmd<cr>
“ error, mapping cannot access script variable 

map bb :execute <SID>cmd<cr>
“ error no variable named <SNR>…cmd 

How to access the script variable in mapping?

vim


Solution 1:[1]

You can provide a script local function and then access to the variable through that function.

let s:var = 'foo'

function! s:get(key) abort
  return get(s:, a:key)
endfunction

nnoremap <silent> ยต :<c-u>echo <sid>get('var')<cr>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luc Hermitte