Add :const for safer scripting #4541
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi all,
This PR has proposed adding
:const
command to Vim.Problem
Scope of variables in Vim script function is very dynamic.
This sometimes causes a bug by modifying variables unexpectedly. To prevent this, (if
i
is intended not to be modified,):lockvar
is effective:However, using
:let
and:lockvar
has following downsides::lockvar
at everywhere it is required:let
and:lockvar
may not be efficient because it introduces overhead of one more command.Solution
In JavaScript,
const
is provided for defining a variable.:const
does the similar thing in Vim script. With it, above example can be written as follows:Here
:const
is used instead of:let
.:const
internally locks the variablei
. Soi
is no longer modifiable. And it is more efficient than using both:let
and:lockvar
because both are done in one command.In addition,
:const
raises an error if the variable is already existing:So
:const
does not lock and overwrite existing variable unexpectedly andx
is guaranteed to be a new variable.Another use case of
:const
would be defining constants in the script. For example:Here the constant is not intended to be modified any more. So
:const
is better than:let
.