lua-users home
lua-l archive

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


Here's what I ended up going with, as it only requires a change to the master file. I'd be interested in comments on why this might be a bad idea.

    ### master.lua
    local m = {}
    local env = getfenv(0)
    setfenv(0,setmetatable({MASTER=m},{__index=env}))

    require 'simple'
    require 'multi'
    require 'shared1'
    require 'shared2'
    require 'reference'
    
    setfenv(0,env)
    return m

All other files are unchanged, except the usage itself which gets a `local MASTER = require 'master'` 

Written up at:
http://stackoverflow.com/q/14942472/405017



On Feb 18, 2013, at 11:42 AM, Kevin Martin <kev82@khn.org.uk> wrote:

On 18 Feb 2013, at 17:46, Gavin Kistner wrote:

> Put more simply: how would you rewrite the following suite of files so that the user can "require 'master'" and not spam the global namespace with "MASTER", but still have all the assertions pass?

I'm not suggesting this is a good idea, but I think it's the simplest way to make it work without any code redesign.

Kev

-- master.lua
assert(package.preload["master.modtbl"] == nil)
package.preload["master.modtbl"] = function ()
return {}
end
local MASTER = require("master.modtbl")

require 'simple'
require 'multi'
require 'shared1'
require 'shared2'
require 'reference'

return MASTER
-- multi.lua
local MASTER = require("master.modtbl")
MASTER.Multi1 = {}
MASTER.Multi2 = {}
-- reference.lua
local MASTER = require("master.modtbl")
function MASTER.Simple:ref1() return MASTER.Multi1 end
function MASTER.Simple:ref2() MASTER:simple() end
-- shared1.lua
local MASTER=require("master.modtbl")
MASTER.Shared = {}
-- shared2.lua
local MASTER = require("master.modtbl")
function MASTER.Shared:go() end
-- simple.lua
local MASTER = require("master.modtbl")
MASTER.Simple = {}
function MASTER:simple() end
-- test.lua
do
local MASTER = require 'master'

assert(MASTER.Simple)
assert(MASTER.simple)
assert(MASTER.Shared)
assert(MASTER.Shared.go)
assert(MASTER.Simple.ref1()==MASTER.Multi1)
assert(pcall(MASTER.Simple.ref2))
end

assert(MASTER == nil)