[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: hex numerical literals in 5.1
- From: Rici Lake <lua@...>
- Date: Thu, 22 Dec 2005 19:40:16 -0500
On 22-Dec-05, at 6:31 PM, Nick Trout wrote:
With the new ... syntax can you do (something like)?
function memoize(func)
return setmetatable({}, {__index =
function(self, ...)
local v = func(...)
self[...] = v
return v
end
}
end
No, sadly. '...' is not a first-class object. You *could* do that with
first-class immutable tuples, but Lua does not seem likely to acquire
such a datatype. You could do this by interning {...} (or, for 5.0,
arg) but the general case of interning {a, b, c} is pretty expensive
in Lua, so it's unlikely that this would be a win without direct
language support.
Python is adding (@) decorators to make this easy. If you could alter
the Lua syntax (token stream) you could do it in Lua:
@memoize
function myexpensivefn(a,b,c) --code-- end
I can actually live with
myexpensivefn = memoize(function(a) ... end)
but I can see the appeal of the Python sugar. However, it should be
noted that memoizing turns a function into a table (of sorts); you can
arrange for the table to have a __call metamethod as well, but that
increases the cost of usage quite a bit.
The fact that the resulting object is technically a table makes it
slightly less general than a real function, since there are various
places in the Lua core where a check is specifically made for the type
TTFUNCTION. For example, a table (even with __call metamethod) cannot
be used as a metamethod itself (except for __index/__newindex, where
the table would be used as a table, with the same functionality.)
Question: should it be possible to distinguish between a table and a
function of one parameter? That is, does Lua really need both foo() and
foo[] syntaxes?