Code walkthroughs

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Anickyan
Prole
Posts: 27
Joined: Sun Aug 05, 2012 8:42 am

Re: Code walkthroughs

Post 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.
User avatar
Roland_Yonaba
Inner party member
Posts: 1563
Joined: Tue Jun 21, 2011 6:08 pm
Location: Ouagadougou (Burkina Faso)
Contact:

Re: Code walkthroughs

Post 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.
User avatar
Robin
The Omniscient
Posts: 6506
Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:

Re: Code walkthroughs

Post 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
Help us help you: attach a .love.
Anickyan
Prole
Posts: 27
Joined: Sun Aug 05, 2012 8:42 am

Re: Code walkthroughs

Post by Anickyan »

Yeah, makes sense. I viewed it as if it was returning a function(I know, wth?).
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 2 guests