每当我用数组做这样的事情时,我都会遇到一个非常恼人的错误.我有代码在love.load()函数中设置数组: function iceToolsInit() objectArray = {} --for object handling objectArrayLocation = 0end 然后是允许创
function iceToolsInit() objectArray = {} --for object handling objectArrayLocation = 0 end
然后是允许创建对象的代码.它基本上抓取了有关所述对象的所有信息并将其插入到数组中.
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
在此之后,更新函数读取objectArray并相应地呈现图像:
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
我当然修剪了一些不需要的代码(只是数组中的额外参数,如宽度和高度),但你得到了要点.当我设置此代码以生成一个对象并呈现它时,我收到此错误:
attempt to index '?' (a nil value)
它指向的这一行是这一行:
renderX = objectArray[arraySearch]["X"]
有谁知道这里有什么问题,以及我将来如何防止它?我真的需要帮助.
这是一个错误:arraySearch = 0 while arraySearch <= arrayLength do arraySearch = arraySearch + 1
你遍历循环arrayLength 1次,经过索引1..arrayLength 1.你想要通过索引1..arrayLength只循环arrayLength次数.解决方案是将条件更改为arraySearch< arrayLength. 另一种(更多Lua-ly方式)是将其写成:
for arraySearch = 1, #objectArray do
更多的Lua-ly方式是使用ipairs和table.field引用而不是(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和movingLeft应该作为参数传递……