Lua:尝试索引零值;避免条件错误

时间:2016-04-08 01:17:39

标签: if-statement lua

我们说我有一张巨大的桌子,如:

test.test[1].testing.test.test_test

表格不保证存在。包含它的表也不是。我想能够做到:

if test.test[1].testing.test.test_test then
   print("it exits!")
end

但是,当然,这会给我一个"尝试索引? (零值)"如果尚未定义任何索引,则会出错。很多次,我最终会做这样的事情:

if test then
   if test.test then
      if test.test[1] then
         if test.test[1].testing then -- and so on

是否有更好,更乏味的方法来实现这一目标?

2 个答案:

答案 0 :(得分:2)

您可以编写一个函数来获取要查找的键列表,并在找到条目时执行您想要的任何操作。这是一个例子:

function forindices(f, table, indices)
  local entry = table

  for _,idx in ipairs(indices) do
    if type(entry) == 'table' and entry[idx] then
      entry = entry[idx]
    else
      entry = nil
      break
    end
  end

  if entry then
    f()
  end
end

test = {test = {{testing = {test = {test_test = 5}}}}}

-- prints "it exists"
forindices(function () print("it exists") end,
           test,
           {"test", 1, "testing", "test", "test_test"})

-- doesn't print
forindices(function () print("it exists") end,
           test,
           {"test", 1, "nope", "test", "test_test"})

另外,解决此类问题的函数式编程概念是Maybe monad。你可以用Lua implementation of monads解决这个问题,虽然它不会很好,因为它没有语法糖。

答案 1 :(得分:2)

您可以通过为nil设置__index元方法来避免引发错误:

debug.setmetatable(nil, { __index=function () end })
print(test.test[1].testing.test.test_test)
test = {test = {{testing = {test = {test_test = 5}}}}}
print(test.test[1].testing.test.test_test)

您还使用空表:

debug.setmetatable(nil, { __index={} })