[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: self (was Colon Operator: Superfluous Syntax?)
- From: Graham Wakefield <lists@...>
- Date: Thu, 15 Mar 2007 14:20:24 -0700
Perhaps a tangent, but I've found myself using this kind of construct  
a good deal:
function apply(o, f, ...)
	setfenv(f, o)
	return f(...)
end
-- example --
obj = { foo = 4 }
meth = function()
	foo = foo + 1 	-- no self or upvalue
end
apply(obj, meth)
print(obj.foo) -- 5
Basically I like the idea of being able to refer to table values  
implicitly within a function, which may be a 'leftover mindset' from  
working in OO languages, may be an aesthetic thing (avoiding lots of  
self. elements in frequently used functions), but maybe also because  
I enjoy the flexibility that Lua environments offer.
I couldn't say what the potential overhead or possible pitfalls of  
this approach are (other than the obvious possibility that obj o does  
not have a member foo etc.)
A more careful implementation would be (untested):
function apply(o, f, ...)
	local e = getfenv(f)
	setfenv(f, o)
	local ret = {f(...)}
	setfenv(f, e)
	return unpack(ret)
end
The apply function could be added to a metatable used by all object,  
or even (if efficiency is not a concern) by all tables.
On Mar 15, 2007, at 12:39 PM, Brian Hagerty wrote:
Kein-Hong Man wrote:
Wow, another hot discussion. Sounds like a religious preference.  
Well, no offense, but if you can convince Guido van Rossum to do  
it first, then maybe I will sit up and pay attention.
You're right, colon-free versus colon-full function definitions is  
probably a religious preference.  If the choice between a dot- 
syntax and a colon-syntax exists, programmers should just choose  
what they are most comfortable with (perhaps because they were used  
to similar syntax in another language).
I personally would like to see a colon-free and hidden argument  
alternative in Lua for object.method calls just for the sake of  
elegance in the language.  I believe this can be easily done with  
an implementation of self that doesn't use the "hidden argument"  
implementation pattern that I described in my previous post.
In any case, it's a wish list item that in fact amounts to a  
religious choice. -- Call me a hidden argument, colon-atheist!
Cheers,
// Brian