为什么我的矩阵值为零?

时间:2014-10-26 11:01:41

标签: lua corona null lua-table

当我尝试在Lua中打印由generateGrid生成的表的值时,我得到nil值(没有错误)。为什么?它不应该返回某种displayObject吗?我打印不正确吗?

local function generateGrid (rows, cols)

    local grid = {}
    local gridPointRadius = 10 -- the display size for the grid points.
    local rowDist = display.contentWidth/(rows-1)
    local colDist = display.contentHeight/(cols-1)

    for row = 1, rows do 
        grid[row] = {}
        for col = 1, cols do

            testCircle =  display.newCircle(rowDist * (row-1), 
                                            colDist * (col-1), 
                                            gridPointRadius) -- ugliness occurs with the offsets and non-zero indexes. how do you prefer use positioning with offsets, when the starting index is 1?
            testCircle:setFillColor( 1,0,0,1 )
            grid[row].col = testCircle -- why does this work, but grid[row][column] does not?
        end
    end
    return grid
end

pathGrid = generateGrid(rowsForGrid, colsForGrid)
print(pathGrid[1][2])

2 个答案:

答案 0 :(得分:2)

grid[row].col = testCircle 

此行是问题所在,grid[row].col相当于grid[row]["col"],这显然不是您想要的,请将其更改为:

grid[row][col] = testCircle 

答案 1 :(得分:1)

您的generateGrid基本上如下:

for row = 1, rows do 
    grid[row] = {}
    for col = 1, cols do
        ...
        grid[row].col = display.newCircle(...)  
    end
end
return grid

" col"之间没有任何关系。在grid[row].colcol循环变量中。表达式grid[row].col查找名为" col"的字段。在grid[row]的对象中,这就像写grid[row]["col"]一样。因此,您发布的代码将在循环中创建的每个显示对象存储在同一个" bin"中,即grid[row]["col"]。但是,print(pathGrid[1][2])正在尝试访问grid[1]的第二项,但没有:grid[1]中唯一的项目是与字段" col"相关联的显示对象。所以打印收到一个零,没有错误:在Lua中,只有当你试图调用一个nil值或访问其中的一个字段时才获得一个不存在的值并不是错误,并且打印不是错误零。如果循环没问题,那么你可以做print(pathGrid[1].col)。修复循环后,您现在拥有的print语句将生成预期的输出。

你也有一个相关的问题"为什么这样做,但是网格[行] [列]没有?":可能因为它不是列而是你应该使用的col,{{ 1}},如果这确实是你使用的那么它应该有效,而与此相关的问题在你的代码中的其他地方。

最后,你要求" ugliness与偏移和非零索引一起出现。当起始索引为1时,你更喜欢使用偏移定位?"当你将从1开始的行(行和列)映射到从0开始的范围(屏幕上的像素)时,没有其他办法。

-