lua-users home
lua-l archive

Re: self copying functions

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


On Fri, Mar 16, 2007 at 07:22:56AM +0900, 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.
Graham:
What about a function do you want to copy?
Functions have state ("closures"/upvalues) that can't be stripped from
them so easily:
 function n()
 local i
	i = i + 1
	return i
 end
 print(n())
 print(n())
 n_copy = n
After you "copy" the function n, what would the relationship be between
n and the copy?
> function copy_fun (fun)
> return function(...) return fun(...) end
> end
> [The extra level of indirection is ever so slightly annoying, but ...]
Miles:
Why would you prefer:
 load_copy = copy_fun(load)
to
 load_copy = load
?
Sam

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