简体   繁体   中英

Emulating c++ 'using namespace' via _ENV

if I have a file 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:

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:

#include <iostream>
using namespace std

In lua I was thinking you could emulate this feature like so:

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. When I wrote the code snippet below in a lua file it did not have give the desired result.

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 )

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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