Page 4 of 4

Re: Code walkthroughs

Posted: Fri Sep 07, 2012 10:52 am
by Anickyan
Roland_Yonaba wrote: Actually it already does thanks to the metatable's __index metamethod

Code: Select all

function Proxy(f)
    return setmetatable({}, {__index = function(self, k)
        local v = f(k)
        self[k] = v
        return v
    end})
end
Or am I missing something ?
I am not sure... I don't think it does.

Re: Code walkthroughs

Posted: Fri Sep 07, 2012 11:07 am
by Roland_Yonaba
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
Try this by yourself. It's only on the first call that Lua enters the body of function __index.
Second and third calls just returns t.z values.

Re: Code walkthroughs

Posted: Fri Sep 07, 2012 11:34 am
by Robin
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

Re: Code walkthroughs

Posted: Fri Sep 07, 2012 2:57 pm
by Anickyan
Yeah, makes sense. I viewed it as if it was returning a function(I know, wth?).