1

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)

Ace shinigami
  • 1,374
  • 2
  • 12
  • 25
  • Using C++ in such a manner is increasingly being considered poor practice. – Aluan Haddad Nov 12 '17 at 22:16
  • 1
    I know the slew of reasons it's unpopular in c++ and I'm not, going to after getting a response to this thread start putting this all over my lua code. I tend to avoid writing code that requires advanced knowledge to understand where possible because it makes the code less readable, and this clearly violates that rule. I was just curious. – Ace shinigami Nov 12 '17 at 22:46

1 Answers1

2

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.

lhf
  • 70,581
  • 9
  • 108
  • 149