首页 > 解决方案 > 为什么这段代码意味着所有表共享一个元表

问题描述

我有一个要求,所有只读表都可以共享一个元表,代码短语回答了这个要求,但我不明白这个代码短语是如何实现这个目标的

local index = {}
local mt = {
  __index = function ( t, k )
    return t[index][k]
  end,

  __newindex = function ( t, k, v )
    -- body
    error("update the value is prohibited",2)
  end
}



function readonly(t)
  local proxy = {}
  proxy[index] = t
  setmetatable(proxy,mt)
  return proxy
end

标签: lualua-table

解决方案


您提供的代码似乎是使用代理表模式的尝试。它可以工作,但它不是“只读表”的有效实现。那是因为您的代理表包含对它应该覆盖的表的引用。它存储在键等于 的字段中index。这意味着人们可以轻松地编辑应该是只读的值,例如:

local A = readonly {foo = 7}
print(A.foo) -- prints: 7
local _,ro = next(A)
ro.foo = 17
print(A.foo) -- prints: 17

“代理表”应该如何工作?简而言之,整个想法是使用一个空表作为用户和只读表之间的代理。我们将带有元方法__index和元方法的元表分配__newindex给代理表。

  • __index每当尝试访问“保存” value 的字段时都会调用nil
  • __newindex每当尝试在表中创建新字段时调用。

由于我们的代理表总是空的,每个赋值都会触发__newindex

local B = readonly {bar = 8}
B.foo = 7 -- non-existent in both proxy and readonly table -> calls __newindex
B.bar = 3 -- exists in readonly table but does not exist in proxy -> calls __newindex

出于同样的原因,每次访问一个字段时__index都会启动:

local B = readonly {bar = 8}
print(B.foo) -- does not exist in proxy, __index is called -> prints "nil"
print(B.bar) -- does not exist in proxy, __index is called -> prints "8"

至于更有效的示例,请参见下文。它仍然存在问题(例如,可以更改表模式以使键变弱;请参阅评论),但至少它涵盖了只读表。

local index = {}

local mt = {
  __index = function (t, k)
    return index[t][k]
  end,
  __newindex = function ()
    -- body
    error("update the value is prohibited",2)
  end,
}

function readonly (t)
  local proxy = {}
  index[proxy] = t
  setmetatable(proxy, mt)
  return proxy
end

如有疑问可以参考:


推荐阅读