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

attempt to perform arithmetic __sub on number and nil

Started by DubSlime, 09 September 2015 - 08:34 AM
DubSlime #1
Posted 09 September 2015 - 10:34 AM
Hi !
I post this topic because I'm encountering a problem programming a program.
I just wanna say that my English could be awful, I'm French, and I'm looking for help from you :)/>
This program take energy information from an Energy Cube, add it in a table called "energy" and will calculate the average energy consumption of my base.
When I run the program, It writes on the screen the following error : "EnergyConsumption:67: attempt to perform arithmetic __sub on number and nil"
There is the parts of the code where the problem si encountered :
First, I set up my tables :
local energy = {}
local diff = {}
p = peripheral.wrap("left")
"energy" will take all the energy measures, E1 = … for the first measure, E2 = … for the second, etc…
"diff" will take the results of the difference between 2 energy measures. For example, diff[1] = energy[2] - energy[1]
So, this is the part of the code where the problem is encountered :
-> Energy measures (currently working, "nac" variable is the number of measures the program will do) :
for i=1, nac do
E = p.getEnergyStored()
energy[i] = E
end
Now, this is the part of the code where the error message goes :
for i=1; nac do
diff[i] = energy[i] - energy[i+1]
end

I hope my English was enough understandable, and I hope you'll can help me too !
HPWebcamAble #2
Posted 09 September 2015 - 11:31 PM
When you add the energy from 'p.getEnergyStored' to the Energy table, it fills the 'energy' table with 'nac' values

When you get the difference from the entries, you do it 'nac' times, BUT, you do it nac+1 times for the last iteration.


Did you get that? If yes, good
If not, then this is your problem:

energy[i+1]
The last time, you'll be trying to get the index 1 PAST where you've created, thus trying to 'index nil'