luacomputercraft

Why does using two variables give me an error message when using an if statement?


I'm attempting to write a script in LUA for the Minecraft mod ComputerCraft. It's supposed to send a turtle down, mine a hole, and place ladders before returning to the surface. I'm trying to make an error display when the turtle doesn't have enough ladders, but I'm receiving an error that prevents it from running. "mineDown :18: attempt to compare string with number expected, got string."

-- This gets the user to tell the turtle how far to dig down
print('How far down should I go?')
distDown = io.read()
distMoved = 0
ladders = turtle.getItemCount(13)

-- Check if the number of ladders is less than the distance needed to move. If so, returns error.
    turtle.select(13)
    if ladders < distDown then
        error('Not enough ladders!')
    end

Solution

  • The error means that ladders is number and distDown is a string. You need to convert them to the same type. For example to convert ladders to a string use tostring or distDown to a number use tonumber:

    if ladders < tonumber(distDown) then