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

attempt to perform arithmetic __mul on nil and number

Started by igelbasis, 25 December 2013 - 03:27 AM
igelbasis #1
Posted 25 December 2013 - 04:27 AM
Hey Guys,

I've got a problem with my rounding function and it doesn't seem to work with the data it receives from the tanks. I'm pretty much sure that it reads the tanks properly as I have tested it several times in the lua prompt. It also worked in other programs. But somehow the rounding function cannot operate with it.

If anyone could tell me what I did wrong I'd be very happy.

Thank you!
Igel


Spoiler[php]rednet.open("top")
local function round(num,idp)
local mult = 10^(idp or 0)
return math.floor(num * mult + 0.5)/mult
end
local function oilTank()
local otank = peripheral.wrap("steel_tank_valve_3")
local oinfo = otank.getTanks("unknown")[1]
local oamount = oinfo["amount"]
local ocapacity = oinfo["capacity"]
if amount == nil then
local ot = 0
else
local ot = (oamount/ocapacity)*100
end
local opt = round(ot, 2)
return opt
end
local function fuelTank()
local ftank = peripheral.wrap("steel_tank_valve_0")
local finfo = ftank.getTanks("unknown")[1]
local famount = finfo["amount"]
local fcapacity = finfo["capacity"]
if famount == nil then
local ft = 0
else
local ft = (famount/fcapacity)*100
end
local fpt = round(ft, 2)
return fpt
end
local function mon()
local m = peripheral.wrap("monitor_3")
return m
end
while true do
local oil = oilTank()
local fuel = fuelTank()
m = mon()
m.setTextScale(1.5)
m.clear()
m.setCursorPos(1,1)
m.write("Oil: "..oil.." %")
m.setCursorPos(1,2)
m.write("Fuel: "..fuel.." %")
end
[/php]
Anavrins #2
Posted 25 December 2013 - 06:41 AM
You're localizing your variables a bit too much, your error come from the "num" variable of your round function being nil because of this…

if famount == nil then
  local ft = 0
else
  local ft = (famount/fcapacity)*100
end
local fpt = round(ft, 2)

You're localizing the "ft" variable within the if statement, so it is not available when you do round(ft,2)
Something like this should work.

local ft

if famount == nil then
  ft = 0
else
  ft = (famount/fcapacity)*100
end
local fpt = round(ft, 2)

Or even better
local ft = (famount == nil) and 0 or ((famount/fcapacity)*100)

I would also recommend you to read about scoping and localizing your variables, here is a good ressource: http://lua-users.org/wiki/ScopeTutorial
Edited on 25 December 2013 - 05:54 AM
igelbasis #3
Posted 25 December 2013 - 09:53 PM
Thanks Anavrins,

it worked and I also read the tutorial about locals.

This topic can be closed.