Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim: undefined variable in a function

Tags:

vim

My .vimrc file includes those following lines:

let read_path = '/var/www/html/readContent.html'
function ReadContentProcess()
    if (expand('%:p') == read_path)
        call feedkeys("\<C-A>")
        call feedkeys("\<C-V>")
    endif
endfunction

When I ran call ReadContentProcess(), I got the following errors:

Error detected while processing fucntion ReadContentProcess:
Line 1:
E121: Undefined variable: read_path
E15: Invalid expression: (expand('%:p') == read_path)

Why? I've defined read_path as a variable, why did vim tell me it didn't exist?

like image 874
Searene Avatar asked Dec 24 '15 03:12

Searene


Video Answer


1 Answers

Variables have a default scope. When defined outside of a function it has the global scope g:. Inside of a function it has a local scope l:. So you need to tell vim which variable you want by prefixing read_path with g:

let read_path = '/var/www/html/readContent.html'
function ReadContentProcess()
    if (expand('%:p') == g:read_path)
        call feedkeys("\<C-A>")
        call feedkeys("\<C-V>")
    endif
end function

From :help g: (and the section after it)

                                                global-variable g:var g:
Inside functions global variables are accessed with "g:".  Omitting this will
access a variable local to a function.  But "g:" can also be used in any other
place if you like.

                                                local-variable l:var l:
Inside functions local variables are accessed without prepending anything.
But you can also prepend "l:" if you like.  However, without prepending "l:"
you may run into reserved variable names.  For example "count".  By itself it
refers to "v:count".  Using "l:count" you can have a local variable with the
same name.
like image 70
FDinoff Avatar answered Oct 16 '22 07:10

FDinoff