Re: __index function in a metatable shared by several tables
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: __index function in a metatable shared by several tables
- From: Ignacio Burgueño <ignaciob@...>
- Date: 2007年10月06日 17:23:40 -0300
Tim Hunter wrote:
Sorry for the vague subject. I don't know better words to summarize my
question.
The following code prints
1
You called foo
Is there any way for the function f to modify o.test? In my code there
could be multiple o tables, all sharing the t metatable. I would like
function f to store state information in each individual o table.
t = {}
setmetatable(t, {__index =
function(_, k)
local function f()
print("You called " .. k)
end
return f
end
})
o = setmetatable({ test=1 }, t)
t.__index = t
print(o.test)
o.foo()
Will this work for you?
mt = {
__index = function(tab, k)
local function f()
print("You called " .. k .." on "..tostring(tab))
tab.test = 20 * math.random()
end
return f
end
}
o = setmetatable({ test=1 }, mt)
o2 = setmetatable({ test=1 }, mt)
print(o.test)
o.foo()
print(o.test)
print(o2.test)
o2.foo()
print(o2.test)
assert(o2.test ~= o.test)