lua-users home
lua-l archive

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

This very issue was a huge problem for me. How do I make do module dependency in a post module era?? What I came up with was the following...


_ENV.lua has all of my common dependancies, such as all of the standard lua libraries (coroutine, table, string, etc, pairs, ipairs, etc). It DOES NOT have any "mymodule" files loaded into it, however. So, a typical module starts with:

_ENV = require'mymoule._ENV'

Now I know I have the same common set of dependencies. This works really well for almost everything. The "almost" part comes when I want to test a submodule from its own file, when that testing requires the loading of the main module. I can't remember, but I think my solution was to not do that anymore...

Anyway, the other thing to keep in mind is the case where you want "self" to be loaded into a sub-module. In that case, what I do is make the return value of my submodule a function, which accepts self. I don't make it accept an _ENV, because I want to keep that to the standard _ENV that I use. This idiom goes something like:

_ENV = require"a._ENV"

return function(self)
  assert(, "bar needs to be set in self, of course!")

  local b = {foo = "baz" .. = "dizzle" }
  return b


when I call it, I use:

self.b = require'a.b'(self)

I could have set `self.b` directly, but I like to always return a table with the new values, just to keep it relatively consistent, even when I'm chaining the function call to the return of require...

Without these tricks, which I may have been badly explaining, I would get constant require-loops, "index to self (a nil value)", and other such crappy-ness. Now it all works and nothing is in the global table!