简体   繁体   中英

Computercraft Lua change nil to 0

I am using Computercraft, a Minecraft mod, and I needed help with something. I am attempting to find all peripherals of a type, get the energy from them, and add them together. However, I get a "attempt to perform arithmetic on nill" or something error. Here is my code:

local periList = peripheral.getNames()
energy = 0
totalenergy = 0

for i = 1, #periList do
  if peripheral.getType(periList[i]) == "cofh_thermalexpansion_energycell" then
    local cell = peripheral.wrap(periList[i])
    print(periList[i])
    if cell.getEnergyStored("potato") ~= "nil" then
      energy = cell.getEnergyStored("potato")
      print(cell.getEnergyStored("potato"))
    else
      energy = 0
      print(0)
    end
    totalenergy = totalenergy + energy
  end
end
print(totalenergy)

Sorry, codebox didn't work

Anyways, does anyone know how to fix this?

nil and "nil" are two different things.

The former is the nil type "singleton" the latter is a string of three characters. They are not equivalent.

Try dropping the quotes from the if line.

Also you can assign (the potential) nil to energy and then directly energy and set it to 0 if it is nil (or even just use

energy = cell.getEnergyStored("potato") or 0

directly since nil is a "false-y" value so nil or 0 evaluates to 0 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM