Vim9: how to invoke callback with additional arguments?

26 views
Skip to first unread message

Lifepillar

unread,
May 30, 2021, 2:12:46 PM5/30/21
to vim...@googlegroups.com
I am trying to understand how to invoke a callback in Vim9 script.
I have started from this example (from the excellent lacygoill's wiki):

vim9script

def Callback(_j: job, _e: number)
echom 'callback'
enddef

def Func()
job_start(['/bin/bash', '-c', ':'], {exit_cb: Callback})
enddef

Func()

That's fine, but now suppose that I want to pass additional arguments to
Callback(). What is Vim9's equivalent of the following?

fun Callback(value, _j, _e)
echom 'callback with value: ' .. a:value
endf

fun Func()
call job_start(['/bin/bash', '-c', ':'],
\ {'exit_cb': function('Callback', [42])})
endf

call Func()

Thanks,
Life.

Bram Moolenaar

unread,
May 30, 2021, 4:18:15 PM5/30/21
to vim...@googlegroups.com, Lifepillar
I don't think there is a difference, you can still use function() to
create a partial.

Is there a "Vim9 way" that would be better? You could use a lambda:

call job_start(['/bin/bash', '-c', ':'],
\ {'exit_cb': (j, e) => Callback(42, j, e)})

It looks a bit nicer. I haven't tried it, you may need to add types.

--
The Law of VIM:
For each member b of the possible behaviour space B of program P, there exists
a finite time t before which at least one user u in the total user space U of
program P will request b becomes a member of the allowed behaviour space B'
(B' <= B).
In other words: Sooner or later everyone wants everything as an option.
-- Vince Negri

/// Bram Moolenaar -- Br...@Moolenaar.net -- http://www.Moolenaar.net \\\
/// \\\
\\\ sponsor Vim, vote for features -- http://www.Vim.org/sponsor/ ///
\\\ help me help AIDS victims -- http://ICCF-Holland.org ///

Lifepillar

unread,
May 31, 2021, 3:16:36 AM5/31/21
to vim...@googlegroups.com
>> What is Vim9's equivalent of the following?
>>
>> fun Callback(value, _j, _e)
>> echom 'callback with value: ' .. a:value
>> endf
>>
>> fun Func()
>> call job_start(['/bin/bash', '-c', ':'],
>> \ {'exit_cb': function('Callback', [42])})
>> endf
>>
>> call Func()
>
> I don't think there is a difference, you can still use function() to
> create a partial.

A definition such as this:

def Func()
job_start(['/bin/bash', '-c', ':'],
\ {'exit_cb': function('Callback', [42])})
enddef

results in `E117: Unknown function: Callback` (in Vim 8.2.2900).

> Is there a "Vim9 way" that would be better? You could use a lambda:
>
> call job_start(['/bin/bash', '-c', ':'],
> \ {'exit_cb': (j, e) => Callback(42, j, e)})
>
> It looks a bit nicer.

I like that. It is explicit about the arguments and it allows me to
reorder the callback's parameters as I see fit. And yes, it works.

Thanks,
Life.

Reply all
Reply to author
Forward
0 new messages