lua-users home
lua-l archive

Re: self

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Ah, of course. So the complete example:
function method(o, func)
	return function(...)
		setfenv(func, o)	-- this has to go inside the returned function
		return func(...)
	end
end
-- example --
obj = { foo = 4 }
test = function()
	foo = foo + 1 	-- no self or upvalue
end
obj.fooIncr = method(obj, test)
obj.fooIncr()
print(obj.foo) -- 5
NB a different approach that doesn't work:
function method(o, func)
	local f = function(...)
		return func(...)
	end
	setfenv(f, o)
	return f
end
Because the setfenv(f, o) doesn't cascade to the func(), because func itself has not been copied, just wrapped. What I really wanted was to duplicate func() completely, and change its environment immediately after, rather than change the environment of the unique func method on each call. I wonder if it makes much difference for performance.
On Mar 15, 2007, at 3:22 PM, Miles Bader wrote:
Graham Wakefield <lists@grahamwakefield.net> writes:
Except that I can't figure out how to make a copy of a function in Lua (or in the Lua API). I guess I need to create a new closure, which I
can do with a cfuntion, but I can't see how to do it with a lua
function.
 function copy_fun (fun)
 return function(...) return fun(...) end
 end
?
[The extra level of indirection is ever so slightly annoying, but ...]
-miles
--
"Whatever you do will be insignificant, but it is very important that
 you do it." Mahatma Gandhi

AltStyle によって変換されたページ (->オリジナル) /