lua-users home
lua-l archive

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


On 9/18/2010 8:52 PM, Tom N Harris wrote:
On 9/17/2010 6:58 AM, Luiz Henrique de Figueiredo wrote:

local cache={}
function mesure(x)
	local y=cache[x]
	if y==nil then
		if x==1 then
			y=0
		elseif x%2==0 then
			y=1+mesure(x/2)
		else
			y=1+mesure(3*x+1)
		end
		cache[x]=y
	end
	return y
end


As a metamethod....

local mesure = setmetatable({0}, {
  __index = function(t,n)
    local y
    if n%2==0 then
      y=1+t[n/2]
    else
      y=1+t[3*n+1]
    end
    t[n]=y
    return y
  end})
for i=1,1000000 do
  length = mesure[i]
  -- etc.
end


This has me puzzled. The above two code snippets are functionally equivalent, right? So why does the metamethod trigger "C stack overflow" while the first one doesn't? They should both have the same recursion depth. I can't find any hidden function calls that may be invoked by the metatable lookup.

--
- tom
telliamed@whoopdedo.org