我不理解 Lua 的弱表

好吧,我想实现一个缓存生成器,它会返回一个句柄,但不会给我实际的数据。

local module = {}

cache = {}
setmetatable(cache, { __mode = "k" })

function getItem(item)
  local result = cache[item] or cacheItem(item)
  return item
end

function cacheItem(item)
  print("缓存项目")
  cache[item] = true
  return cache[item]
end

function printCache()
  for key, value in pairs(cache) do
    print(key.name .. " 和 " .. value)
  end
end

module.printCache = printCache
module.getItem = getItem

return module

但当我尝试使用它时:

local module = require("./cache")

a = {
  name = "Jimmie"
}

function foo()
  local b = {
    name = "Bobbie"
  }

  local h1 = module.getCachedItem(a)
  module.getCachedItem(b)
  local h3 = module.getCachedItem({ name = "Lenny" })

  module.printCache()
end

foo()
module.printCache()

第一次回合,我期望打印出所有的名字。 第二次回合,我只期望打印出 "Jimmie"。 然而所有的名字都被打印了两次。lua -v 返回 5.2.4。

点赞