lua-users home
lua-l archive

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


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)