尝试比较字符串和数字 - Computercraft

    local level = 3 -- 需要的访问级别
local sideIn = "bottom" -- Keycard 输入面
local sideOut = "right" -- 红石输出面
local rsTime = 3 -- 红石时间
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("> 访问已授权")
        disk.eject(sideIn)
        rs.setOutput(sideOut,true)
        sleep(rsTime)
        rs.setOutput(sideOut,false)
        else
        print("> 权限被拒绝")
        disk.eject(sideIn)
        end
    end
end

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

.temp:15: 尝试比较字符串和数字,应该是数字,但得到了字符串

有人知道如何解决这个问题吗?我放了一个 nil 检查器,但似乎不起作用。你们有什么想法怎么解决这个问题?我已经尝试了至少半个小时,但我还是毫无头绪。

点赞
用户10461421
用户10461421

在这个部分中:

    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 不是同一个变量,因此第一个 code 不受影响。在 else 中,第二个 code 的块终止,当条件为假时,elseend 之间发生了同样的事情。为了不将值 0tonumber(code) 分配给新变量,你必须从 local code = ... 中删除 local。因此,以下是正确的写法:

local level = 3 -- 所需访问级别
local sideIn = "bottom" -- Keycard 输入端口
local sideOut = "right" -- 红石输出端口
local rsTime = 3 -- 红石时间
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("> 已授权访问")
            disk.eject(sideIn)
            rs.setOutput(sideOut,true)
            sleep(rsTime)
            rs.setOutput(sideOut,false)
        else
            print("> 权限被拒绝")
            disk.eject(sideIn)
        end
    end
end
2018-12-31 14:39:15