简体   繁体   English

通过_ENV模拟C ++“使用命名空间”

[英]Emulating c++ 'using namespace' via _ENV

if I have a file foo.lua : 如果我有一个文件foo.lua

local foo = {}
foo.add = function(a, b) return a+b end
foo.sub = function(a, b) return a-b end
foo.multiply = function(a, b) return a*b end
return foo

and in bar.lua I make heavy use of code from foo.lua I am bothered by typing foo.add() all the time and would prefer to write just add() in bar.lua I can add this: bar.lua我大量使用了foo.lua的代码,我一直foo.lua输入foo.add() ,而宁愿在bar.lua只写add() ,也可以添加以下代码:

local foo = require('foo')
local add, sub, multiply = foo.add, foo.sub, foo.multiply

but that begins to be a pain when you are including aliasing many values from many files. 但是当您包含对多个文件中的多个值进行别名时,这开始变得很痛苦。 In c++ there is a way around this: 在c ++中,有一种解决方法:

#include <iostream>
using namespace std

In lua I was thinking you could emulate this feature like so: 在lua中,我认为您可以像下面这样模拟此功能:

local foo = require('foo')
setmetatable(_ENV, {__index = foo})

from what I can tell it respects scope so thing like the code below play nice: 据我所知,它尊重范围,因此下面的代码可以很好地发挥作用:

actually the code below does not work. 实际上下面的代码不起作用。 I was running the code through the lua repl. 我正在通过lua repl运行代码。 When I wrote the code snippet below in a lua file it did not have give the desired result. 当我在lua文件中编写以下代码片段时,它没有给出所需的结果。

f = function() -- returns 2
    setmetatable(_ENV, {__index = foo})
    return add(1, 1)
end 
add(1, 1) -- returns 2

is there any reason I might regret doing this? 有什么理由让我后悔吗? (other than reasons that also appy to using namespace ) (除了也适用于using namespace原因)

Changing the global environment is not polite to other libraries. 改变全球环境对其他图书馆而言并不客气。

Try the other way around: 尝试另一种方法:

do
  local _ENV = setmetatable(foo, {index = _ENV})
  print(add(1, 1))
end

Note that add will be resolved in foo and print in the original _ENV . 请注意, add将在foo解析,并在原始_ENV print

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM