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

Index expected: got nil BUT ITS DECLARED

Started by thelargecactus, 29 August 2015 - 12:02 AM
thelargecactus #1
Posted 29 August 2015 - 02:02 AM
I have been working on a program that keeps a big reactor multiblock in equilibrium by managing the levels of input and output fluid and trying to optimize based on temperature. For this, I am using a few arrays that let me better keep track of average values that I get from some of the sensors. I have written this snippet of my code to initialize the 10 elements of 2 arrays to all 0 so that it doesnt return nil whenever I average it for the first few ticks. I attempted to initialize the values below as described below but I get an error on line '2' ( as relative to how it is pasted) that says "<programname>:<2>: index expected, got nil. I assumed that putting index = 1 would initialize the variable 'index' to 1 and so it should not be nil. But the interpreter says that it is. What am I doing wrong and how can I fix it?
  • for index=1,10,1 do
  • tempArray[index] = 0
  • fluidArray[index] = 0
  • end
Lyqyd #2
Posted 29 August 2015 - 02:03 AM
Did you declare the tempArray table, though?
thelargecactus #3
Posted 29 August 2015 - 02:12 AM
I am unsure of what a table is, but I did try declaring the array with a different method above that loop and it still didnt work
  • tempArray[10] = {0,0,0,0,0,0,0,0,0,0}
  • fluidArray[10] = {0,0,0,0,0,0,0,0,0,0}
Lyqyd #4
Posted 29 August 2015 - 02:15 AM
It should be:


local tempArray = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
thelargecactus #5
Posted 29 August 2015 - 02:28 AM
Ok that makes sense, now how would I declare it in a loop?
Lyqyd #6
Posted 29 August 2015 - 05:17 AM
You'd use your original code, but before the loop, you'd declare the tables:


local tempArray = {}
local fluidArray = {}
MKlegoman357 #7
Posted 29 August 2015 - 07:48 AM
Just to make it clear: there are no arrays in Lua. There are only tables. Make sure to read about them here.
Bomb Bloke #8
Posted 29 August 2015 - 08:17 AM
… which, while true, is pretty ironic when you consider that the table API only contains functions that're relevant to arrays.