0

If I have a function that takes a range, how can I echo the return value of the function?

For example, the following does not work:

:echo 2,8call MyFunction()

3 Answers 3

4

I looked into this, and I could not find a direct way of doing it. However, one possibility is to create an auxiliary function, that is:

function! Range() range abort
  return RangeAux(a:firstline, a:lastline)
endfunction

function! RangeAux(lnum1, lnum2) abort
  echo a:lnum1
  echo a:lnum2
endfunction

1,3call Range()
call RangeAux(1,3)
3

@Karl's answer is pretty good but you can also use execute():

echo execute("1,2call Range()")

You can even use variables for the range:

let l1=1
let l2=2
echo execute(l1 . "," . l2 . "call Range()")
4
  • Thanks! I think this is closer to answering the original question. Very neat! Commented Feb 5, 2018 at 12:10
  • 1
    @KarlYngveLervåg I don't know which answer is closer to the original question: mine is shorter to write but I find yours more pleasant to read :)
    – statox
    Commented Feb 5, 2018 at 12:40
  • I could not get this to work. It just echoes a blank line. The return value is not echoed. Did you test this with a trivial function? Commented Feb 6, 2018 at 11:25
  • 1
    This should not work since the return value of execute(command) is what is to be echoed by the command. Here the command 1,2call Range() does not echo anything so execute() return ''. Basically, using call you are not be able to get the return value, unless you set a global variable instead of using return.
    – doraemon
    Commented Dec 13, 2018 at 7:58
1

Using call you are not able to get the return value of the function, regardless whether range is used or not.

Aside from @Karl's answer, you can set some variable instead of using return. Such as

function! Range() range abort
  let toreturn = 'my value'
  let s:retval = toreturn
endfunction
1
  • Yes, you can get the return value from the function using call(). From :h call(): Returns the return value of the called function. {dict} is for functions with the "dict" attribute. It will be used to set the local variable "self". |Dictionary-function| Commented Dec 20, 2021 at 21:19

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.