Tuesday, September 21, 2010

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

On Tue, 21 Sep 2010, Bee wrote:

> On Sep 21, 3:30 pm, "Israel Chauca F." wrote:
>> On Sep 21, 2010, at 5:02 PM, Bee wrote:
>>
>>> why use "let str = a:str" in a function
>>
>>> Looking at some functions, I have seen "let str = a:str"
>>
>> a:vars are read-only, read  :h a:var  for more details.
>
> Thank you, I missed the read-only part when reading about a:var

I missed that, too. Thanks.


> 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

No. That's using 'Curly braces names':

:help curly-braces-names

In Perl, that's a "symbolic reference". PHP calls them "variable
variables" (oh, PHP).

> Is one better than the other?
>
> function! Inc(var)
> let var = a:var
> let var += 1
> return var
> endfunction

Your second example doesn't have the same effect. The one using the
"curly braces name" updates a variable, then returns its value. It's
using 'a:var' to hold the name of a variable. In your second example,
you're using the value of 'a:var' as a number.

:help internal-variables

See the effect of the curly-braces-name in the following example:

function! Inc(var)
let {a:var} += 1
return {a:var}
endfunction

let g:a = 1

echo "g:a =" g:a
echo "Inc(g:a) =" Inc('g:a')
echo "g:a =" g:a

" output:
" g:a = 1
" Inc(g:a) = 2
" g:a = 2

--
Best,
Ben

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