Dreamy115
Dreamy115

Reputation: 31

attempt to compare string with number - computercraft

    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

When there's no disk inserted, it throws an error:

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

Does anyone know how to fix this issue? I throwed in a nil checker but it seems to not work. Any ideas on how could I fix this? I've been trying for at least half an hour now, and I still have no clue.

Upvotes: 3

Views: 5478

Answers (1)

EpichinoM2
EpichinoM2

Reputation: 137

In this section:

    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

It first makes a new local variable with local code = .... In the new block that you create with the if, you also create new local variables with local code = .... Since it has the same name as the local before it, it "masks" it, prohibiting you from accessing the first code in the rest of the block. The value that you assign 0 to is not the same variable outside the if, so the first code is unaffected. At else the block for the second code ends and the same thing happens between else and end when the condition is false. To not assign the values 0 or tonumber(code) to new variables, you have to remove the local from local code = .... So the following is what it should be:

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

Upvotes: 3

Related Questions