lua table - Lua 5.2 metatables and environment -
i've got structure 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 users enter code ui , code pasted update
functions of different modules, after local _env
set. user-entered code should sandboxed. should able access few functions (the ones in context
table) , contents of other modules. code in m1:update
should able refer variables in m1.variables
without qualifying them; variables in other modules (ie ones in m2.variables
) should accessible qualifying them module name (ie m2.x
).
but result this:
$ lua -i test.lua > = modules.m1.x 1 > = modules.m1.variables.x 1 > = modules.m2.x 1 > = modules.m2.variables.x 1 > = modules.m1:update() > = modules.m1.x 2 > = modules.m1.variables.x 2 > = modules.m2.x 2 > = modules.m2.variables.x 1
why modules.m2.variables.x
not getting updated? , if, seems, modules.m2.x
different modules.m2.variables.x
, modules.m2.x
coming from?
modules.m2.variables.x
not getting updated because set __index
metamethod (which used when retrieving non-existing key), not __newindex
metamethod (which used when assigning value non-existent key), , result value stored in modules.m2.x
table , not modules.m2.variables.x
table intended.
if add __newindex
in setmetatable(modules.m2, {__index = modules.m2.variables, __newindex = modules.m2.variables})
, expected result.
Comments
Post a Comment