lua-users home
lua-l archive

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


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 }))