Search code examples
vimviml

Passing a dictionary to a function in viml


I'm building a custom unite.vim source one of the choices should be able to call a function that can accept a dictonary

function! s:source.gather_candidates(args, context) abort "{{{
  let l:nodeInfo = a:context.file
  return [
        \{
        \ 'word': 'delete the current node',
        \ 'kind': 'command',
        \ 'source': s:source.name,
        \ 'action__command': 'call DeleteNode(' . l:nodeInfo .')',
        \ }]
endfunction "}}}

And then to just test it out, echo the dictionary

function! DeleteNode(node) abort "{{{
  let l:currentNode = a:node
  echo l:currentNode
endfunction "}}}

But when I attempt to load my source, I get

Vim(return):E731: using Dictionary as a String

How can I pass the dictionary (around 24 keys) to the function?


Solution

  • EDIT: As romainl pointed out, you should be able to use :echo with a dictionary, unlike :echomessage. In that later case, you'll have needed to stringify your dictionary with string() function.

    Thus I suspect a similar problem with the building of the action command. I'm not sure about the type of this nodeInfo data, but I suspect a dictionary. In case this is indeed a dictionary, you'll have to build the action__command dictionary entry with: 'call DeleteNode(' . string(nodeInfo) .')', or you could also use the new Partials (:h Partial, IIRC) if your version of Vim is recent enough (7.4.1558+), and if the code that executes this entry also supports funcrefs. They'll be much simpler to use, but definitively not portable to Vim 7.3 nor to vim 7.4.9xx...