docs: More on dereferencing variables

This commit is contained in:
Fabian Boehm 2024-04-05 18:41:09 +02:00
parent 0a6e8468cc
commit 1a4bb851ff

View file

@ -750,7 +750,23 @@ The ``$`` symbol can also be used multiple times, as a kind of "dereference" ope
``$$foo[$i]`` is "the value of the variable named by ``$foo[$i]``". ``$$foo[$i]`` is "the value of the variable named by ``$foo[$i]``".
When using this feature together with list brackets, the brackets will be used from the inside out. ``$$foo[5]`` will use the fifth element of ``$foo`` as a variable name, instead of giving the fifth element of all the variables $foo refers to. That would instead be expressed as ``$$foo[1..-1][5]`` (take all elements of ``$foo``, use them as variable names, then give the fifth element of those). This can also be used to give a variable name to a function::
function print_var
for arg in $argv
echo Variable $arg is $$arg
end
end
set -g foo 1 2 3
set -g bar a b c
print_var foo bar
# prints "Variable foo is 1 2 3" and "Variable bar is a b c"
Of course the variable will have to be accessible from the function, so it needs to be :ref:`global/universal <variables-scope>` or :ref:`exported <variables-export>`. It also can't clash with a variable name used inside the function. So if we had made $foo there a local variable, or if we had named it "arg" instead, it would not have worked.
When using this feature together with :ref:`slices <expand-slices>`, the slices will be used from the inside out. ``$$foo[5]`` will use the fifth element of ``$foo`` as a variable name, instead of giving the fifth element of all the variables $foo refers to. That would instead be expressed as ``$$foo[1..-1][5]`` (take all elements of ``$foo``, use them as variable names, then give the fifth element of those).
Some more examples:: Some more examples::