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
:constcommand 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
iis intended not to be modified,):lockvaris effective:However, using
:letand:lockvarhas following downsides::lockvarat everywhere it is required:letand:lockvarmay not be efficient because it introduces overhead of one more command.Solution
In JavaScript,
constis provided for defining a variable.:constdoes the similar thing in Vim script. With it, above example can be written as follows:Here
:constis used instead of:let.:constinternally locks the variablei. Soiis no longer modifiable. And it is more efficient than using both:letand:lockvarbecause both are done in one command.In addition,
:constraises an error if the variable is already existing:So
:constdoes not lock and overwrite existing variable unexpectedly andxis guaranteed to be a new variable.Another use case of
:constwould be defining constants in the script. For example:Here the constant is not intended to be modified any more. So
:constis better than:let.