1

I'm having trouble using one Lua lib from inside another. I'm not sure about the best way to do it.

I've got a library that returns a (non-global) table with functions, like this:

-- foo.lua
local foo = {}
function foo:m1(...) ... end
function foo:m2(...) ... end
return foo

This library can be inserted in either the global or local scope, depending on what the user wants:

-- globally
foo = require('foo')
-- or locally
local foo = require('foo')

I'm now trying to create another lib (let's call it bar) that requires/uses this foo lib. Something like this:

-- bar.lua
local bar={}
function bar:m3(...)
  ...
  foo:m1()
  ...
end

My trouble is - I don't know how to "pass" foo to bar.

Ideally I'd like to send it as a parameter to require:

local foo = require('foo')
local bar = require('bar', foo)

But I don't think that's possible (is it?). The other option I could think about was adding a init method to bar:

local foo = require('foo')
local bar = require('bar')
bar:init(foo)

This works, but doesn't look very clean to me; it's possible to forget adding that third line, leaving bar in an "unsafe" state.

Is there a common Lua idiom/method that I'm missing?

kikito
  • 51,734
  • 32
  • 149
  • 189

1 Answers1

6

Just call require 'foo' directly in you bar module. This is perfectly legal. The foo module will be loaded only once. In order not to leak it out of the bar module, store it in a local variable.

You can use this idiom also to separate one big module into several parts, and have one module require all the others. The user will have to require only one module.

Michal Kottman
  • 16,375
  • 3
  • 47
  • 62
  • But of course! How didn't I think about that! I'll try `require 'foo'` from `bar`, and if that fails, I'll get bar's "path" and try ´require(path .. '.foo')´, else error. Thanks! – kikito Oct 30 '11 at 10:57