Lua / LOVE Indexing Issues

I get a very annoying error when I do something similar with arrays. I have code that sets an array in the love.load () function:

function iceToolsInit() objectArray = {} --for object handling objectArrayLocation = 0 end 

and then code that allows you to create an object. It basically captures all the information about the specified object and inserts it into an array.

 function createObject(x, y, renderimage) --used in the load function --objectArray is set up in the init function objectArrayLocation = objectArrayLocation + 1 objectArray[objectArrayLocation] = {} objectArray[objectArrayLocation]["X"] = x objectArray[objectArrayLocation]["Y"] = y objectArray[objectArrayLocation]["renderimage"] = love.graphics.newImage(renderimage) end 

After that, the update function reads the objectArray object and accordingly displays the images:

 function refreshObjects() --made for the update function arrayLength = #objectArray arraySearch = 0 while arraySearch <= arrayLength do arraySearch = arraySearch + 1 renderX = objectArray[arraySearch]["X"] renderY = objectArray[arraySearch]["Y"] renderimage = objectArray[arraySearch]["renderimage"] if movingLeft == true then --rotation for rightfacing images renderRotation = 120 else renderRotation = 0 end love.graphics.draw(renderimage, renderX, renderY, renderRotation) end end 

Of course, I cut off some unnecessary code (just additional parameters in the array, such as width and height), but you get the gist. When I create this code to create one object and render it, I get this error:

 attempt to index '?' (a nil value) 

the line this line points to:

 renderX = objectArray[arraySearch]["X"] 

Does anyone know what is wrong here, and how could I prevent this in the future? I really need help with this.

+4
source share
1 answer

This is an error at a time:

 arraySearch = 0 while arraySearch <= arrayLength do arraySearch = arraySearch + 1 

You loop arrayLength+1 number of times you go through the indices 1..arrayLength+1 . You want to go through the loop only arrayLength number of times with indices 1..arrayLength . The solution is to change the condition to arraySearch < arrayLength .

Another (more Lua-ly way) should write this as:

 for arraySearch = 1, #objectArray do 

Another Lua-ly way is to use the ipairs and table.field link instead of ( table["field"] ):

 function refreshObjects() for _, el in ipairs(objectArray) do love.graphics.draw(el.renderimage, el.X, el.Y, movingLeft and 120 or 0) end end 

objectArray and movingLeft should probably be passed as parameters ...

+6
source

Source: https://habr.com/ru/post/1501873/


All Articles