1

In vimscript, when I want to store the return value of a function, I do

let a:foo = Function()

But I now have a ranged function. I would like to store its return value, ideally via something like the following:

let a:foo = l:start,l:end call RangedFunction()

(this does not work, but it illustrates my objective)

Attempts/ideas

  1. Using execute, this calls my function, but does not let me save its return value. There must be a tricky smart way to get this to work, but it feels pretty heavy.
execute a:start.",".a:end." call RangedFunction()"
  1. I could pass the range lines as two explicit arguments directly in the function.
function RangedFunction(start,end) 

but then I couldn't call my function using :10,12call RangedFunction(), which is a flexibility I'd like to keep, and it would make my function implementation heavier.

This is probably a syntax thing I've missed while searching the doc, but it keeps escaping me !

1

1 Answer 1

2

I'm not sure this is possible.

I only see a workaround for now where you could define 2 functions as 12,42let someresult = RangeFunction() is not supported.

function! Function(firstline, lastline) abort
  " where the code is actually defined
  return getline(a:firstline, a:lastline)
endfunction

function RangeFunction() range abort
  " the version that is meant to be used from commands
  return Function(a:firstline, a:lastline)
endfunction

" Usage 1
command! -range RangeCommand <first>,<last>call RangeFunction()
" Usage 2
let lines = Function(12, 42)

Honestly, I find strange a function that returns important information that will get discarded when called from a command, and saved when used as an expression. It's quite likely the reason why this isn't supported: the calling syntax would be much to cumbersome. Imagine let expr = f1,l1 call('Function1', ['other', 'parameters']) + f2,l2 call('Function2', []). It's better to keep the code simple.

PS: :let a:whatever = 42 shall not be possible. Only Vim is authorized to assign values to formal parameters.

1
  • Thank you for your answer ! You make a good point. I will rethink my script ! I was trying to get the best of both worlds: being able to use my function as a standalone (easier to use... and debug !), and being able to use it as a utility function for other functions.
    – Feffe
    Commented Jun 10 at 8:57

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.