Skip to content

add function scope option to the set command #565

@xiaq

Description

@xiaq

Doc of set builtin says:

The scoping rules when creating or updating a variable are:

  1. If a variable is explicitly set to either universal, global or local, that setting will be honored. If a variable of the same name exists in a different scope, that variable will not be changed.
  2. If a variable is not explicitly set to be either universal, global or local, but has been previously defined, the previous variable scope is used.
  3. If a variable is not explicitly set to be either universal, global or local and has never before been defined, the variable will be local to the currently executing function. Note that this is different from using the -l or –local flag. If one of those flags is used, the variable will be local to the most inner currently executing block, while without these the variable will be local to the function. If no function is executing, the variable will be global.

The upside is that well-known global variables ($PATH, $EDITOR, etc.) can be set within functions without an explicit -g. However, the behavior of the following function can be confusing:

function f
    set var val
end

If the user has a global variable named var, this function alters the global environment. Otherwise it has no impact on global environment. To make the function safe one has to always write

function f
    set -l var val
end

which is quite tedious. Therefore I propose that set should always imply function scope within functions.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions