Wednesday, September 22, 2010

Re: why use "let str = a:str" in a function

On Sep 21, 10:00 pm, Bee <200...@calcentral.com> wrote:
>
> The :help a:var does say "However, if a |List| or |Dictionary| is
> used, you can change their contents."
>
> I found this example function. Is {a:var} now a Dictionary?
>
> function! Inc(var)
>   let {a:var} += 1
>   return {a:var}
> endfunction
>
> Is one better than the other?
>
> function! Inc(var)
>   let var = a:var
>   let var += 1
>   return var
> endfunction
>

As Ben H. says, these are NOT an example of using a:var as a
dictionary. He gives an excellent explanation of what these two
functions actually do, but here's an example of a function that uses a
dictionary:

function! Inc(var)
let a:var.value += 1
return a:var.value
endfunction

Call it like this:

let my_dict = { 'value' : 1 }
echo Inc(my_dict)

This sort of thing allows for object-oriented constructs, as well as
other uses.

Basically it's saying that dictionaries and lists are always passed by
reference. If you want to pass by value you'll need to copy them
first:

echo Inc(deepcopy(my_dict))

See :help copy() and :help deepcopy().

--
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

No comments: