【问题标题】:Computercraft Lua change nil to 0Computercraft Lua 将 nil 更改为 0
【发布时间】:2014-09-05 08:16:03
【问题描述】:

我正在使用 Minecraft 模组 Computercraft,我需要一些帮助。我试图找到一种类型的所有外围设备,从中获取能量,然后将它们加在一起。但是,我收到“尝试对 nill 执行算术”或其他错误。这是我的代码:

local periList = peripheral.getNames()
energy = 0
totalenergy = 0

for i = 1, #periList do
  if peripheral.getType(periList[i]) == "cofh_thermalexpansion_energycell" then
    local cell = peripheral.wrap(periList[i])
    print(periList[i])
    if cell.getEnergyStored("potato") ~= "nil" then
      energy = cell.getEnergyStored("potato")
      print(cell.getEnergyStored("potato"))
    else
      energy = 0
      print(0)
    end
    totalenergy = totalenergy + energy
  end
end
print(totalenergy)

抱歉,密码箱不起作用

无论如何,有人知道如何解决这个问题吗?

【问题讨论】:

    标签: lua computercraft


    【解决方案1】:

    nil"nil" 是两个不同的东西。

    前者是nil类型“singleton”,后者是三个字符的字符串。它们不是等价的。

    尝试从if 行中删除引号。

    您还可以将(潜力)nil 分配给energy,然后直接将energy 设置为0,如果它是nil(或者甚至只是使用

    energy = cell.getEnergyStored("potato") or 0
    

    直接因为nil 是一个“false-y”值,所以nil or 0 的计算结果为0)。

    【讨论】:

    • 是的,只需删除引号即可。谢谢!如何标记为已解决?
    • @NathanielButterfield 答案旁边的投票箭头下应该有一个复选标记,您可以单击以接受答案。
    猜你喜欢
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多