lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> So I went ahead and implemented that little command line utility. I
> think it is better to isolate the core file filtering from the vim
> plugin. I might be able to use vim's lua interface to code the plugin,
> but maybe it will be better to use plain old vimscript and call the
> external utility. Not sure yet.

If your command line utility uses print() to report its results, you can
intercept the output of the script when executed using the Lua Interface
for Vim using Vim's :redir command.

I'm attaching two files, a Vim plug-in and a Lua module. The plug-in
will call the module using the Lua Interface for Vim if available, but
fall back to executing an external Lua interpreter process. Here's a
usage example of how you can call the function defined by the plug-in
(just type this into Vim).

  :call confirm(InvokeLua('myluamod', "Vim calls Lua"))

 - Peter Odding

PS. When the Lua Interface for Vim encounters a syntax error or similar
while loading the Lua module, the require() call will return false and
keep doing so (very annoying) unless you execute the following in Vim:

  :lua package.loaded.myluamod = nil
" Save this file in ~/.vim/plugin on UNIX or %USERPROFILE\vimfiles\plugin on
" Windows. This Vim plug-in defines a single function which can be used to
" call a Lua module. If the Lua interface for Vim is available that will be
" used, otherwise the Lua interpreter will be run as an external process. The
" function takes the name of the module to call and an arbitrary string like a
" keyword or the lines in the current buffer.

function! InvokeLua(module, input)
  if has('lua')
    let cmd = "silent lua require '%s' (vim.eval 'a:input')"
    redir => output
      execute printf(cmd, a:module)
    redir END
  else
    let cmd = 'lua -e "require ''%s'' (io.read ''*a'')" 2>&1'
    let output = system(printf(cmd, a:module), a:input)
    if v:shell_error
      let msg = "Failed to invoke Lua module %s: %s"
      throw printf(msg, a:module, output)
    endif
  endif
  return output
endfunction
-- Save this file somewhere in your $LUA_PATH (package.path).
-- This is a Lua module to be called from Vim. It should return
-- a function that acts as the entry point for the module:

return function(input)
  print(input)
  print "Lua reports to Vim"
end