How to remove a variable from child script environment in lua?

712 Views Asked by At

I have a script which I load with loadfile and then run it. Also I have the variable love in the scope of parent lua script and I want this variable be nil inside the child script enivornment but everything else untouched (print, math, pairs, all the std lib of Lua). How can I do that?

This does not work:

local scenario = love.filesystem.load(script)
local env = {}
setmetatable(env, { __index = _G })
env.love = nil
env.game = Game
setfenv(scenario, env)
2

There are 2 best solutions below

4
lhf On BEST ANSWER

Your code does not work because env inherits from _G and so env.love is resolved in _G. Setting env.love = nil does not add a love entry to env.

Set env.love = false or env.love = {}.

4
Egor   Skriptunoff On
local scenario = love.filesystem.load(script)
local env = setmetatable({}, { __index = 
   function(t, k)
      if k == "love" then
         return nil
      else
         return _G[k]
      end
   end
})
setfenv(scenario, env)