有没有记载`require`在全局环境中运行块? [英] Is it ever documented that `require` runs chunks in the global env?
问题描述
编写模块时,文件在全局环境中运行,而不是在调用环境中运行:
When you write a module, the file is run in the global environment, not the calling environment:
-- other_file.lua
require('my_file')
-- my_file.lua
getfenv(2) == getfenv(0) -- true
setfenv(1, {}) -- or module(...)
getfenv(2) == getfenv(0) -- true
我永远都不记得读过这本书.是否在任何地方提到/记录了?
I don't ever remember reading about this. Is it mentioned/documented anywhere?
(此问题更多地是关于require
而不是getfenv
.我知道它已在5.2中删除.)
(This question is more about require
rather than getfenv
. I know it's removed in 5.2.)
推荐答案
它没有明确记录,但是在没有任何确切说明的情况下,您应该假定它像Lua的其余部分一样工作,即使用全局环境.
It is not explicitly documented but in the absence of any precise statement you should assume that it works like the rest of Lua, that is, using the global environment.
dofile
还在全局环境中而不是在调用环境中运行文件.换句话说,dofile
与include
不同,而Lua没有.
dofile
also runs the file in the global environment, not in the calling environment. In other words, dofile
is not the same as include
, which Lua does not have.
require
本质上是dofile
的一个版本,它支持路径并缓存加载的文件.因此,它还在全局环境中而不是在调用环境中运行文件.
require
is essentially a version of dofile
that supports paths and caches loaded files. So, it also runs the file in the global environment, not in the calling environment.
这篇关于有没有记载`require`在全局环境中运行块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!