lua-users home
lua-l archive

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


On Mon, Feb 18, 2013 at 11:46 AM, Gavin Kistner <phrogz@me.com> 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?
>
>     ### _test_usage_.lua
>     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))
>

Having read the thread after I gave my answer, sigh.... I like Petite
Abeille's answer the most, although it requires a rewrite of
everything I"ve done.

Using my method, I've come up with a solution to your extremely
out-there example:

--_test_usage_.lua
print(package.path)
package.path = package.path .. ';./?.lua;./?/init.lua'
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))

print(MASTER)
print(_G.MASTER)

-->  table: 0x7ff613408e70
-->  nil

--master.lua
local MASTER = {}
MASTER = require 'simple'(MASTER)  --you MADE ME DO THIS!! Yuck.
MASTER = require 'multi'(MASTER)
MASTER.Shared = require'shared1'
MASTER = require'shared2'(MASTER)
MASTER = require 'reference'(MASTER)

return MASTER
--simple.lua
return function(MASTER)
	MASTER.Simple = {}
	function MASTER:simple() end
	return	MASTER
end
--multi.lua
return function(MASTER)
	MASTER.Multi1 = {}
	MASTER.Multi2 = {}
	return MASTER
end
--reference.lua
return function(MASTER)
	function MASTER.Simple:ref1() return MASTER.Multi1 end
	function MASTER.Simple:ref2() MASTER:simple()      end
	return MASTER
end
--shared2.lua
return function(MASTER)
	function MASTER.Shared:go() end
	return MASTER
end

--shared1.lua
return {}

-----------

It's one of those compact examples that was carefully crafted to cover
every use case and, as a result, left me angry when I was done solving
it. I now need to shower, although I mean no disrespect to your
illustrating example.

That is to say, if you think my solution looks worse than yours,
consider that your example is purpose-conceived to be difficult, not
useful in real life. In real life, doing these kinds of things is just
bad design, although one or two in of each in a single project is
certainly possible.

-Andrew