lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Thomas Lauer writes:
> with this module...I get some weird results...
> The rawget() call in checkglobals() is too restrictive, methinks. How
about changing this call to env[name]:

Hmm... env[name] is what I had.  There isn't any rawget in my patch, but a
rawget in there would explain the difference you saw.  Check my original patch.

> checkglobals() doesn't work well if two or more modules are defined
> in one file.

Here's two solutions I can think of:

-- file: example1.lua  (stronger checking--preferred)
;(function()
  module('one', package.seeall)
  function foo() print('foo') end
  checkglobals()
end)()

;(function()
  module('two', package.seeall)
  function bar() print('bar') end
  one.foo()
  checkglobals()
end)()

-- file: example2.lua  (weaker checking)
module('one', package.seeall)
function foo() print('foo') end

module('two', package.seeall)
function bar() print('bar') end
one.foo()

function multitable(tables)
  return setmetatable({}, {
    __index = function(_,k)
      local result
      for _,t in ipairs(tables) do
        result = t[k]
        if result ~= nil then return result end
      end
    end
  })
end
checkglobals(nil, multitable{one, two})
--


Note that in example1, it would not be possible to add checkglobals() at the
bottom of the file.  checkglobals() assumes that lexically nested functions have
the same environment as the parent function.  A simpler example:

  local t = {one='uno'}
  local f = setfenv(function() return one end, t)
  print(f())
  checkglobals()  -- raises: 'one' undefined

If that is an issue, one could write t.one or (getfenv()).one rather than one,
not use checkglobals for that file, use partial checking as in example2, or
maybe (better) workout some solution to selectively ignore that nested function.
 For example, checkglobals() could be modified accept another optional parameter
to ignore lexically nested functions:

  checkglobals(f, env, opt) -- opt = 'norecurse'

That would require a small change accordingly to the proposed patch to
debug.getinfo (but no change to lbci).