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?