如何将值从嵌套函数返回朱莉娅的主脚本?

发布于 2025-02-03 15:04:01 字数 221 浏览 2 评论 0原文

例如:

函数main()

function doit()
    A = ones(Int, 2) 
    return A
end

doit()
display(A) 
A = [1, 2, 3] 
display(A)
doit()
display(A)

另外,如果嵌套函数具有两三层,我们如何将局部变量值返回MAIN或将其保存到MAIN中?

For example:

function main()

function doit()
    A = ones(Int, 2) 
    return A
end

doit()
display(A) 
A = [1, 2, 3] 
display(A)
doit()
display(A)

Also what if the nested function has two or three layers, how can we return local variable values into main or save them into main?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

咽泪装欢 2025-02-10 15:04:01

引入HAR的功能,因此在外面没有看到通常在其中定义的变量。
就您的情况而言,我知道您希望函数doit()具有突变全局变量的外部效果。

虽然不建议使用全局变量,并且这种副作用通常不是优雅的模式,但可以通过使用global关键字来轻松实现:

function doit()
    global A = ones(Int, 2) 
    return A
end

在这种情况下,您的Julia会话可能看起来像:

julia> doit();

julia> display(A)
2-element Vector{Int64}:
 1
 1

julia> A = [1,2,3];

julia> doit();

julia> display(A)
2-element Vector{Int64}:
 1
 1

有关更多信息,您可以使用现在需要看看朱莉娅(Julia)中的可变范围工作: https:/ /docs.julialang.org/en/v1/manual/variobles-and-scoping/

Functions in introduce ha hard scope so normally variables defined within them are not seen outside.
For your case I understand that you want the function doit() have an external effect of mutating a global variable.

While the use of global variables is discouraged and such side effects are generally not elegant pattern, it can be easily achieved by using global keyword:

function doit()
    global A = ones(Int, 2) 
    return A
end

in that case your Julia session could look like:

julia> doit();

julia> display(A)
2-element Vector{Int64}:
 1
 1

julia> A = [1,2,3];

julia> doit();

julia> display(A)
2-element Vector{Int64}:
 1
 1

For more information, you need to have a look now variable scoping works in Julia: https://docs.julialang.org/en/v1/manual/variables-and-scoping/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文