This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
ShoeLace1291's profile picture

Why am I getting a "expected number" error?

Started by ShoeLace1291, 16 February 2020 - 01:42 AM
ShoeLace1291 #1
Posted 16 February 2020 - 02:42 AM
I am working on a turtle program that's supposed to build 4 walls. For some reason, I am getting the error "Expected number". The code from the line that the error is thrown from is code that I've used before(turtle.refuel(1) in other programs so I'm kind of confused right now. Forgive my ignorance on the subject, I have little experience with Lua. I'll point out in the code where the error is.



write("How wide should the room be?")
local x = tonumber(read())
write("How long should the room be?")
local y = tonumber(read())
write("How tall should the room be?")
local z = tonumber(read())

write("Place fuel in slot 1 and whatever building block you want to use in the rest and press enter to continue")

read()

function go()
    turtle.forward()
    slot = checkSlots()
    turtle.select(slot)
    turtle.placeUp()
    checkFuel()
end

function checkFuel()
    if turtle.getFuelLevel() == 0 then
        turtle.refuel(1) [b] --Error happens here[/b]
    end
end

function checkSlots()
    for s=2,16,1 do
        if turtle.getItemCount(s) > 0 then break end
    end
    return s
end

for h=0,z,1 do
  for i=0,1,1 do
    for w=0,y,1 do
        go()
    end
    turtle.turnRight()
    for l=0,x,1 do
        go()
    end
    turtle.turnRight()
  end
  turtle.digDown()
  turtle.down()
end
Luca_S #2
Posted 16 February 2020 - 06:21 AM
Are you sure the Error is happening at turtle.refuel(1)? Because that should work, however your checkSlots function will always return nil, so turtle.select(slot) will break.

The problem is the scope of the variable s. It is only visible inside of the for loop, I would suggest changing your function to this:

function checkSlots()
	for s=2,16,1 do
		if turtle.getItemCount(s) > 0 then
		  return s
		end
	end
end


Also, after calling checkSlots() you should check wether the result is nil, in case there are no Blocks anymore.
Edited on 17 February 2020 - 03:02 PM
ShoeLace1291 #3
Posted 17 February 2020 - 10:50 PM
that did the trick. thanks very much!
ShoeLace1291 #4
Posted 18 February 2020 - 01:00 AM
Also, after calling checkSlots() you should check wether the result is nil, in case there are no Blocks anymore.

Isn't that what turtle.getItemCount(s) does?
Luca_S #5
Posted 18 February 2020 - 12:41 PM
Also, after calling checkSlots() you should check wether the result is nil, in case there are no Blocks anymore.

Isn't that what turtle.getItemCount(s) does?

If all slots from 2 to 16 are empty your function won't return anything, which will cause turtle.select(slot) to error.