lua-users home
lua-l archive

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



On 22-Dec-05, at 12:19 PM, Roberto Ierusalimschy wrote:

O = {}
setmetatable(O, {__index = function (t, k)
  k = string.match(k, "^x(.*)")
  local v = tonumber(k, 16)
  t[k] = v
   ^^ You need to memoize the original k, not the modified one.
  return v
end})

print(O.x34)    --> 52

(O.x34 is "almost" 0x34 :) The memoizing is important in real programs,
where many constants appear inside functions and loops (and therefore
are evaluated multiple times).

I agree. Maybe memoize should be in the standard library; it's incredibly
useful, and having it around would avoid some easily avoidable errors.

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

Although this doesn't correctly handle the case where 'v' is nil (or
at least it doesn't memoize the nil), and it doesn't protect itself
from errors during the execution of 'func'.