在整个文件的闭包中看不到局部变量? [英] local variable cannot be seen in a closure across the file?
问题描述
假设我有以下两个Lua文件:
Suppose I have the following two Lua files:
在a.lua
中:
local x = 5
f = dofile'b.lua'
f()
在b.lua
中:
local fun = function()
print(x)
end
return fun
然后,如果我在shell中运行luajit a.lua
,它会显示nil
,因为在b.lua
定义的函数中看不到x
.预期的打印应为5
.但是,如果我将所有内容都放在一个文件中,那正是我想要的:
Then if I run luajit a.lua
in shell it prints nil
since x
cannot be seen in the function defined in b.lua
. The expected printing should be 5
. However if I put everything in a single file then it's exactly what I want:
在aa.lua
中:
local x = 5
local f = function()
print(x)
end
f()
运行luajit aa.lua
,它会显示5
.
那么为什么在第一种情况下看不到x
?
So why x
cannot be seen in the first case?
推荐答案
顾名思义,局部变量对于块而言是局部的.
As their name suggests, local variables are local to the chunk.
dofile()
从另一个文件加载块.由于它是另一个块,因此第一个块中的局部变量x
未被它看到是有道理的.
dofile()
loads the chunk from another file. Since it's another chunk, it makes sense that the local variable x
in the first chunk isn't seen by it.
这篇关于在整个文件的闭包中看不到局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!