lua-users home
lua-l archive

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


> O = memoize(function(str) return tonumber(str:match"^x(%x+)$") end)
> 
> where:
> 
> function memoize(func)
>    return setmetatable({}, {__index =
>      function(self, k)
>        local v = func(k)
>        self[k] = v
>        return v
>      end
>    }
> end

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

function myexpensivefn(a,b,c) --code-- end
foo = memoize(myexpensivefn)
foo(1,2,3) -- calculated
foo(1,2,3) -- cached

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

myexpensivefn (1,2,3) -- calculated
myexpensivefn (1,2,3) -- cached


Nick