lua-users home
lua-l archive

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


I've got a slightly complex structure of tables, metatables and
__index tables.  A sketch of it, enough to show the problem, looks
like this:

context = {
  pi = math.pi,
  sin = math.sin,
  cos = math.cos,
  tan = math.tan,
  print = print
}

modules = {
  m1 = {
    variables = { x = 1 },
    update = function(self)
      local _ENV = self.variables
      x = 2
      m2.x = 2
    end
  },
  m2 = {
    variables = { x = 1 },
    update = function(self)
      local _ENV = self.variables
    end
  }
}

setmetatable(modules.m1, {__index = modules.m1.variables})
setmetatable(modules.m1.variables, {__index = context})

setmetatable(modules.m2, {__index = modules.m2.variables})
setmetatable(modules.m2.variables, {__index = context})

setmetatable(context, {__index = modules})


The idea here is that I have a UI where users define modules, their
variables and a bit of code for each module.  I generate the list of
variables for each module and paste the code into the `update`
function.  Their code should be able to access a few functions (those
in the `context` object), variables from the module the code is in
without qualification (ie as `x`) and variables from other modules
qualified with the name of the module (ie as `m2.x`).

But it doesn't work quite how I expect:

assert(modules.m1.x == 1)
assert(modules.m1.variables.x == 1)
assert(modules.m2.x == 1)
assert(modules.m2.variables.x == 1)
modules.m1:update()
assert(modules.m1.x == 2)
assert(modules.m1.variables.x == 2)
assert(modules.m2.x == 2)
assert(modules.m2.variables.x == 2)
lua: test2.lua:42: assertion failed!
stack traceback:
    [C]: in function 'assert'
    test2.lua:42: in main chunk
    [C]: in ?

When I inspect it, `modules.m2.variables.x` is still 1.

What's going on here?  Why does modules.m2.variables.x not get
changed?  If modules.m2.x and modules.m2.variables.x are not the same,
as it seems they aren't, then what is modules.m2.x and where does it
come from?

Thanks for any help; I'm a bit lost as to what I'm doing wrong.
Tom