【问题标题】:How to fix "attempt to index a nil value"如何修复“尝试索引零值”
【发布时间】:2019-07-26 01:52:04
【问题描述】:

我的代码有一个错误:它一直告诉我“尝试索引一个零值(全局'边')”

我正在尝试通过 Minecraft (OpenComputers) 学习 Lua,但发现自己陷入了零值问题。可能有些东西实际上不是来自 Lua(mod 本身),但问题涉及“纯 Lua 部分”

component = require("component")
event = require("event")
computer = require("computer")
term = require("term")

gpu = component.gpu

redstone = component.redstone

gpu.setResolution(160,50)

while true do
    term.clear()
    term.setCursor(1,1)
    gpu.setBackground(0x5A5A5A)

    gpu.set(1,1," Allumer lampe    Eteindre lampe")
    term.setCursor(1,2)

    local _,_,x,y = event.pull("touch")

    if x >= 2 and x <= 14 and y == 1 then
        redstone.setOutput(sides.left,15)
    elseif x >= 19 and x <= 32 and y == 1 then
        redstone.setOutput(sides.left,0)
    else
        main()

    end

end

我去了 mod 的 Wiki,它说 redstone.setOutput(sides.left,15) 应该改变输出的实际值,但它也返回输出的 OLD 值(这就是我认为我做错了)

【问题讨论】:

    标签: lua null minecraft opencomputers


    【解决方案1】:

    在你的代码方面没有定义。

    因为你有这行:

    redstone.setOutput(sides.left,15)
    

    您尝试使用索引运算符 . 索引 sides 的位置

    由于 sides 在此范围内的 nil 值中是未知的,因此您无法对其进行索引。那没有意义。

    Lua 会在错误消息中抱怨您的尝试。

    为避免此错误,您必须确保不索引 nil 值,方法是不对其编制索引或在编制索引时确保它不是 nil。

    Sides API 是一个可以根据需要加载的模块。 有一些代码可以在表中创建该 API。

    local sides = require("sides")
    

    将执行该代码并将对新创建的 API 表的引用存储在局部变量 sides 中。

    这样做之后,索引sides 是合法的,因为sides 不再是nil,而是一个表。

    sides.left 将引用存储在表 sides 中的值作为键 "left"

    【讨论】:

    • 太棒了!也感谢您分享解释,希望其他人也能这样做
    【解决方案2】:

    this page 所述,您必须先致电require,就像在这个sn-p 中一样:

    local component = require("component")
    local sides = require("sides")
    local rs = component.redstone
    rs.setOutput(sides.back, rs.getInput(sides.left))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-12
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 2015-10-25
      相关资源
      最近更新 更多