Thursday, July 14, 2016

Re: vim function argument

Hi,

Yang Luo schrieb am 14.07.2016 um 08:41:
>
> I write a function like this:
> function InsertNumber(start, end, step)
>
> let i = a:start
>
> let curr_line = 0
>
> while i <= a:end
> if a:step <= 0
> echo "Error: step cannot <=0."
> break
> endif
>
> call append(curr_line, i)
>
> let i += a:step
>
> let curr_line += 1
>
> endwhile
> endfunction
>
>
> when I call this function, I type this:
> :echo InsertNumber(8,10,1)
> 8
> 9
> 10
>
>
> 1) How can I give arguement "step" a default value(eg: 1) when define the function?
> like a C function:
> void C_func(int a, int b_have_default_val = 1)
> {
>
> ;
> }

you can use optional arguments like this

function InsertNumber(start, end, ...)
if a:0 == 0
let l:step = 1
else
let l:step = a:1
endif
...
endfunction

> 2)
> I want to print number like this, how to do it?
> 08
> 09
> 10

Use the printf() function:

call appendline(curr_line, printf('%02d', i))

Or if your numbers can have more than two digits:

let width = trunc(log10(a:end)) + 1
let format = '%0' . width . 'd'
call appendline(curr_line, printf(format, i))


Regards,
Jürgen

--
Sometimes I think the surest sign that intelligent life exists elsewhere
in the universe is that none of it has tried to contact us. (Calvin)

--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment