Searene
Searene

Reputation: 27544

vim: undefined variable in a function

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?

Upvotes: 7

Views: 6576

Answers (1)

FDinoff
FDinoff

Reputation: 31419

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.

Upvotes: 10

Related Questions