【问题标题】:Lua table not accessible (attempt to index a nil value)Lua 表不可访问(尝试索引一个 nil 值)
【发布时间】:2018-12-25 18:10:05
【问题描述】:

我有一张如下所示的表格:

{
  block_0 = {
    hash = "98d1a61c4e3d6394b2970a2a5c44ec2caf172ad5c6844b114867b31fa528220e",
    index = 0
  }
}

难道我不能通过说chain["block_0"]["hash"] 来访问block_0indexhash 值吗?它不工作。当我使用这条线时,我收到错误attempt to index a nil value (field 'block_0')。如何正确访问hashindex

编辑:这里有更多上下文:

function add_thing()
  block_name = "block_0"
  block = { }
  block[block_name] = { }
  block[block_name]["hash"] = ""
  block[block_name]["index"] = ""
  block[block_name]["hash"] = "this is a test hash"
  block[block_name]["index"] = 10
  return block
end

chain = { }
table.insert(chain, add_thing())
require 'pl.pretty'.dump(chain)

【问题讨论】:

  • 你能提供更多的上下文吗?您的代码如何使用此 blob?
  • 完成。 @CurtisF。
  • chain[1]["block_0"]["hash"] 或者你的意思是local chain = add_thing()

标签: lua


【解决方案1】:

您将add_thing 的返回值插入chain。因此链现在是一张表。要索引正确的字段,您必须首先索引chain,即chain[1]["block_0"]["hash"]。我宁愿怀疑这不是预期的行为,您想要执行以下操作

local function add_thing(chain)
  local block_name = "block_0"
  chain[block_name] = {
    hash = "this is a test hash",
    index = 10
  }
end

local chain = {}
add_thing(chain)
print(chain["block_0"]["hash"]) -- this is a test hash

Live on Wandbox

这按预期工作,因为表是引用类型。

【讨论】:

  • 我需要使用local
  • @MattX 您不必这样做,但建议将变量保留在使用它们的地方。
猜你喜欢
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
  • 2016-05-09
  • 2012-08-01
  • 2019-08-21
  • 2015-10-25
  • 1970-01-01
相关资源
最近更新 更多