Lua - Repeat until 递归表格以除外 '试图索引空值'

好的,我会举个例子

我想做这个:

local x = {}

repeat
-- 等待函数
until x.lel.ciao

但是我得到了这个错误: input:3: attempt to index a nil value (field 'lel')

所以我只能这样做:

local x = {}

repeat
-- 等待函数
until x.lel and x.lel.ciao

但是如果我有一个很长的路径该怎么办? 比如: x.lel.ciao.value1.title1.text1 我不想这样做:

local x = {}

repeat
-- 等待函数
until x.lel and x.lel.ciao and x.lel.ciao.value1 and x.lel.ciao.value1.title1 and x.lel.ciao.value1.title1.text1

有人有想法吗?像一个函数 safepath(x.lel.ciao.value1.title1.text1)

点赞
用户13955436
用户13955436

就像 Egor 的评论所说的(感谢 Egor),debug.setmetatable 允许您为对象类型设置元表(而不是对象实例)。

这带来了一个问题,

同一类型的所有对象都将继承该元表。

这意味着,您将遇到会使您的代码更难调试的问题,因为从 nil 值获得这种反馈显然很重要。

以以下代码为例:

debug.setmetatable(nil, { __index = {} })
repeat
    . . . -- Your code goes here
until x.lel.ciao.value1.title1.text1

function getFrom(data, value)
    return date[value]
end

. . . -- More code

从这个简单的作用域角度来看,你可能很快就能看到问题,但想象一下这段代码 被数千行和函数所淹没

你最终会因为它始终返回 nil 而疯掉,这根本不应该发生,因为,嗯,你确定你的 data 变量有这个值,对吧?

为了避免这种情况发生,您应该像这样安全地执行它:

debug.setmetatable(nil, { __index = {} })
repeat
    . . . -- Your code goes here
until x.lel.ciao.value1.title1.text1
debug.setmetatable(nil, nil)

根据 Lua 参考资料,将元表设置为 nil 将删除元表,这样您只会在重复循环内部运行时临时忽略从 nil 得到的反馈。

2020-08-20 06:46:00