【问题标题】:Why is my matrix value nil?为什么我的矩阵值为零?
【发布时间】:2014-12-21 17:29:04
【问题描述】:

当我尝试在 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])

【问题讨论】:

    标签: lua coronasdk null lua-table


    【解决方案1】:
    grid[row].col = testCircle 
    

    这行是问题所在,grid[row].col相当于grid[row]["col"],显然不是你想要的,改成:

    grid[row][col] = testCircle 
    

    【讨论】:

      【解决方案2】:

      您的generateGrid 实质上如下:

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

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

      您还有一个相关的问题“为什么它有效,但 grid[row][column] 无效?”:可能是因为您应该使用的不是 column 而是 col,grid[row][col],如果确实如此你使用的东西应该可以工作,与此相关的问题在你的代码中的其他地方。

      最后,您问“偏移量和非零索引会出现丑陋。当起始索引为 1 时,您更喜欢如何使用偏移量定位?”:当您映射从 1 开始的范围时,没有其他方法(行和列)到从 0 开始的范围(屏幕上的像素)。

      --

      【讨论】:

      • 感谢您对细节的难以置信的关注!非零索引让我有点发疯,但是...... :)
      猜你喜欢
      • 1970-01-01
      • 2022-11-29
      • 2020-11-05
      • 1970-01-01
      • 2021-12-30
      • 2018-11-22
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多