【问题标题】:attempt to compare string with number - computercraft尝试将字符串与数字进行比较 - 计算机技术
【发布时间】:2018-12-31 22:39:15
【问题描述】:
    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

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

【问题讨论】:

  • local code = tonumber(code)中删除local

标签: lua computercraft


【解决方案1】:

在本节中:

    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 的块结束,当条件为假时,elseend 之间也会发生同样的事情。要不将值 0tonumber(code) 分配给新变量,您必须从 local code = ... 中删除 local。所以应该是这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多