在整个文件的闭包中看不到局部变量? [英] local variable cannot be seen in a closure across the file?

查看:70
本文介绍了在整个文件的闭包中看不到局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下两个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屋!

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