I am not sure... I don't think it does.Roland_Yonaba wrote: Actually it already does thanks to the metatable's __index metamethod
Or am I missing something ?Code: Select all
function Proxy(f) return setmetatable({}, {__index = function(self, k) local v = f(k) self[k] = v return v end}) end
Code walkthroughs
Re: Code walkthroughs
- Roland_Yonaba
- Inner party member
- Posts: 1563
- Joined: Tue Jun 21, 2011 6:08 pm
- Location: Ouagadougou (Burkina Faso)
- Contact:
Re: Code walkthroughs
Anickyan wrote:I am not sure... I don't think it does.
Code: Select all
t = setmetatable({}, {__index = function(self,k)
print(('Key %s missing! So __index will create a new one!'):format(k))
self[k] = true
return self[k]
end})
print('Call 1', t.z)
--> Key z missing! So __index will create a new one!
--> Call 1 true
print('Call 2', t.z)
--> Call 2 true
print('Call 3', t.z)
--> Call 3 true
Second and third calls just returns t.z values.
- Robin
- The Omniscient
- Posts: 6506
- Joined: Fri Feb 20, 2009 4:29 pm
- Location: The Netherlands
- Contact:
Re: Code walkthroughs
However, if we change it:
Code: Select all
t = setmetatable({}, {__index = function(self,k)
print(('Key %s missing! So __index will create a new one!'):format(k))
-- note we do not change self
return true
end})
print('Call 1', t.z)
--> Key z missing! So __index will create a new one!
--> Call 1 true
print('Call 2', t.z)
--> Key z missing! So __index will create a new one!
--> Call 2 true
print('Call 3', t.z)
--> Key z missing! So __index will create a new one!
--> Call 3 true
Help us help you: attach a .love.
Re: Code walkthroughs
Yeah, makes sense. I viewed it as if it was returning a function(I know, wth?).
Who is online
Users browsing this forum: Bing [Bot] and 2 guests