Lua表的备用值(整个表)

我相信答案是“不行”,但我还是需要问一下:

我有几个嵌套的值表,大多数都具有相同的“架构”(名称层次结构)。 例如,theme.person.child在这些嵌套表中的每个表中都有一个值,例如像“#ffcc33”这样的字符串。

有时,我想能够引用theme.person(通常是表格)并“获取”字符串值而不是名称。 我想要一个所有person的默认值,而不管子键如何。

是否有任何元方法/键可以让我在table.person.childtable.person上调用相同的函数并始终获取字符串? 在代码中:

local theme1 = { person = { child='#ffcc33', adult='#00ffff', _default='#ff0000' } }
local theme2 = { person = '#ff0000' }
for _,theme in ipairs{ theme1, theme2 } do
    print(somefunction(theme))
end

是否有任何方法可以使两个打印语句输出#ff0000? 除了:

function somefunction(x) return type(x)=='table' and x._default or x end
点赞
用户369792
用户369792

这里用的方式有点奇怪,但是这是你想要的吗?person必须是硬编码属性,或者如果它们是一个表格,你想要在所有属性中搜索_default吗?

local theme1 = { person = { child='#ffcc33', adult='#00ffff', _default='#ff0000' } }
local theme2 = { person = '#ff0000' }

function somefunction(tbl, param)
  if type(tbl) == 'string' then return tbl end
  return tbl._default
end

for _,theme in ipairs{theme1, theme2} do
  print(somefunction(theme.person))
end

codepad

你可以使用 元表,如果有一个标准,你想要使用它,但然后必须在每个表上设置它们。__tostring 用于元表,它允许在将表转换为字符串时返回任何你想要的字符串。在下面的代码中,我在theme1person上设置了元表,以便在对表执行tostring()时返回 _default__index 让你可以在表被索引时返回任何值。在这里,它像一个color属性,如果person是一个表,则返回 person._default,否则返回 person

local personmt = {
  __tostring = function(t)
    if type(t) == 'table' and t._default ~= nil then return t._default end
    return tostring(t)
  end
}

local thememt = {
  __index = function(t, k)
    if k == 'color' then
      if type(t.person) == 'table' then return t.person._default end
      return t.person
    end
  end
}

local theme1 = { person = { child='#ffcc33', adult='#00ffff', _default='#ff0000' } }
local theme2 = { person = '#ff0000' }

setmetatable(theme1.person, personmt)

for _,theme in ipairs{ theme1, theme2 } do
    setmetatable(theme, thememt)
    print('theme.person (__tostring):', theme.person)
    print('theme.color (__index)    :', theme.color)
end

codepad

2018-07-27 07:15:12