3
    local level = 3 -- Required access level
local sideIn = "bottom" -- Keycard Input Side
local sideOut = "right" -- Redstone output side
local rsTime = 3 -- Redstone time
while true do
if disk.isPresent(sideIn) then
        term.clear()
        term.setCursorPos(1,1)
        local code = fs.open("disk/passcode.lua", "r").readAll()
        if code == nil then
        local code = 0
        else
        local code = tonumber(code)
        end
        if code >= level then
        print("> Access Granted")
        disk.eject(sideIn)
        rs.setOutput(sideOut,true)
        sleep(rsTime)
        rs.setOutput(sideOut,false)
        else
        print("> Permission Denied")
        disk.eject(sideIn)
        end
    end
end

当没有插入磁盘时,它会抛出一个错误:

.temp:15: attempt to compare string with number expected, got string

有谁知道如何解决这个问题?我扔了一个零检查器,但它似乎不起作用。关于如何解决这个问题的任何想法?我已经尝试了至少半个小时,但我仍然没有任何线索。

4

1 回答 1

3

在这个部分:

    local code = fs.open("disk/passcode.lua", "r").readAll() --(1)
    if code == nil then
    local code = 0 --(2)
    else
    local code = tonumber(code) --(3)
    end

它首先使用 . 创建一个新的局部变量local code = ...。在您使用 创建的新块中if,您使用创建新的局部变量local code = ...。由于它与之前的本地名称相同,因此它“屏蔽”它,禁止您访问code块其余部分中的第一个。您分配 0 的值与 之外的变量不同if,因此第一个code不受影响。在else第二个块code结束时,同样的事情发生在条件为假之间else和之间。end要不分配值0tonumber(code)新变量,您必须删除localfrom local code = ...。所以应该是这样的:

local level = 3 -- Required access level
local sideIn = "bottom" -- Keycard Input Side
local sideOut = "right" -- Redstone output side
local rsTime = 3 -- Redstone time
while true do
    if disk.isPresent(sideIn) then
        term.clear()
        term.setCursorPos(1,1)
        local code = fs.open("disk/passcode.lua", "r").readAll()
        if code == nil then
            code = 0
        else
            code = tonumber(code)
        end
        if code >= level then
            print("> Access Granted")
            disk.eject(sideIn)
            rs.setOutput(sideOut,true)
            sleep(rsTime)
            rs.setOutput(sideOut,false)
        else
            print("> Permission Denied")
            disk.eject(sideIn)
        end
    end
end
于 2018-12-31T14:39:15.120 回答