On 20 Dec 2012 09:48, "Geoff Leyland" <
geoff_leyland@fastmail.fm> wrote:
Hi,
I'm tidying up some code and moving towards compatibility with 5.2. In particular, I'm getting rid of "module". I have some code where file A requires file B, and file B in turn requires file A. I used to get around this with a bit of require ordering and the fact that "module" filled in package.loaded early. Without module that doesn't work.
At the moment, I'm considering requiring one of the modules inside the function that actually uses it, so it gets initialised on first use, which, really, all seems a bit of overkill.
Can anyone point me to the obvious and simple solution?
Below is a sort of test case of the code - a little system for evaluating expressions. As one file, it works (with a forward declaration of add) but if I cut it into modules at the "-----" markers and start using require, there's a require loop. Surely I'm missing something?
Cheers,
Geoff
----- _expression_.lua
local add
--local add = require("add")
local _expression_ = {}
_expression_.__index = _expression_
function _expression_:new(o)
return setmetatable(o or {}, self)
end
function _expression_.__add(a, b)
return add:new{a, b} -- I could 'require("add")' it here?
end
function _expression_.eval(exp, vars)
local mt = getmetatable(exp)
local f = mt and mt.__eval
return (f and f(exp, vars)) or exp
end
-- return _expression_
----- ref.lua
-- local _expression_ = require("_expression_")
local ref = _expression_:new()
ref.__index = ref
ref.__add = _expression_.__add
function ref:__eval(vars)
return vars[self[1]] or self
end
function ref:__tostring()
return self[1]
end
-- return ref
----- add.lua
-- local _expression_ = require("_expression_")
add = _expression_:new()
add.__index = add
add.__add = _expression_.__add -- _expression_.__add is used here
function add:__eval(vars)
local a = _expression_.eval(self[1], vars)
local b = _expression_.eval(self[2], vars)
if a == self[1] and b == self[2] then return self end
return a + b
end
function add:__tostring()
return tostring(self[1]) .. " + " .. tostring(self[2])
end
-- return add
----- main.lua
-- local _expression_ = require("_expression_")
-- local require("ref")
local R = setmetatable({}, { __index = function(t, k) return ref:new{k} end })
print(_expression_.eval(R.a + R.b, { b = 2 }))