使用来自“子代"的局部变量.职能 [英] Using local variables from "child" functions

查看:46
本文介绍了使用来自“子代"的局部变量.职能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

function child()
{
    echo $var
}

function parent()
{
    local var=5
    child
}

我已经在我的机器上对其进行了测试,它似乎可以运行,但是我找不到任何明确描述这种局部变量用法的东西.即,当我在一个函数中声明局部变量并从该函数中调用其他函数时,是否可以在后者中使用该变量(甚至将其嵌套得更深)?在bash中合法吗,并且对于所有版本都是标准的吗?

I've tested it on my machine and it seems to work but I wasn't able to find anything definitive describing such usage of local variables. Namely, when I declare a local variable in one function and from that function I call some other function, can I use the variable in the latter (and even nest it deeper)? Is it legal in bash and is it standard for all versions?

推荐答案

bash 使用动态作用域. child 中的 var 的值不是由定义 child 的位置确定的,而是由调用的位置确定的.如果 child 的主体中没有本地定义,则外壳程序查找的下一个位置是从中调用 child 的函数的主体,依此类推. local 修饰符在该调用本地的函数中创建一个变量,因此它不会影响任何封闭范围中的变量值.但是,对于任何封闭的范围,它都是可见的.

bash uses dynamic scoping. The value of var in child is not determined by where child is defined, but by where it is called. If there is no local definition in the body of child, the next place the shell looks is in the body of the function from which child is called, and so forth. The local modifier creates a variable in a function that is local to that call, so it does not affect the value of the variable from any enclosing scopes. It is, though, visible to any enclosed scope.

a () { echo "$var"; }
b () { local var="local value"; a; }

var="global value"
a  # outputs "global value"
b  # outputs "local value"

这篇关于使用来自“子代"的局部变量.职能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆