如何使用Lua中的表初始化表?

如何使用Lua中的表初始化表?,lua,lua-table,love2d,minesweeper,Lua,Lua Table,Love2d,Minesweeper,我和一个朋友尝试使用Löve框架在Lua中编写一个扫雷程序。到目前为止,代码需要查看是否选中了框(单元格),然后绘制它。我们是Lua的新手,该程序现在有一个缺陷,它只在右下角的框中工作 更新:现在查看它,我看到初始化的GameBoard的值都具有相同的值(即,GameBoard[1]tillGameBoard[150]都是相同的单元格) 代码如下: conf.lua定义了一些全局变量: function love.conf(t) -- Global variables. CEL

我和一个朋友尝试使用Löve框架在Lua中编写一个扫雷程序。到目前为止,代码需要查看是否选中了框(单元格),然后绘制它。我们是Lua的新手,该程序现在有一个缺陷,它只在右下角的框中工作

更新:现在查看它,我看到初始化的GameBoard的值都具有相同的值(即,
GameBoard[1]
till
GameBoard[150]
都是相同的单元格)

代码如下:

conf.lua
定义了一些全局变量:

function love.conf(t)

    -- Global variables.
    CELL_SIZE = 40
    NUM_ROWS = 15
    NUM_COLS = 10
    STATS_HEIGHT = 100
    AMOUNT_OF_CELLS = NUM_ROWS * NUM_COLS
    GRID_WIDTH = 400
    GRID_HEIGHT = 700

end
以下是
main.lua中的相关失败代码(在加载方法中,
GameBoard
填充了
单元格时出错)

--  The Cell table is used for every individual square on 
--  the gameboard
Cell = {}

-- The Gameboard (150 Cell objects)
GameBoard = {}

--  The function new belongs to Cell and spawns a new object (a table)
--  with the same attributes as Cell.
function Cell:new(i, j)

--  each cell knows:
    --  its x- and y-coordinates.
    self.x_min = (i-1) * CELL_SIZE 
    self.x_max = (CELL_SIZE-1) + (i-1) * CELL_SIZE
    self.y_min = STATS_HEIGHT + (j-1) * CELL_SIZE 
    self.y_max = STATS_HEIGHT + (CELL_SIZE-1) + (j-1) * CELL_SIZE

    --  if it is a mine (determined with random number generator)
    isMine =  (math.random(1, 8) % 8 == 0) -- Roughly 0.15 (1/7) times true (is a mine)
    self.isMine = isMine

    --  do not check the mine initially
    self.checked = false

    --  return the cell object
    return self;

end


--  love.load is a love-function that is called once when the game
--  starts.
function love.load()

    -- The index of the cell on the GameBoard (ranging from 1 to 150)
    local index = 1

    --  Build a two dimensional table of Cell-objects
    for i = 1, NUM_COLS, 1 do
        for j = 1, NUM_ROWS, 1 do       
            GameBoard[ index ] = Cell:new( i, j )
            index = index + 1
        end
    end
end
结果是,所有框都具有索引为150的下框的值(自
NUM_ROWS*NUM_COLS
=150以来的最新值)。表(
Gameboard
)的所有元素(
Cells
)都具有在
Cell:new
方法中设置的x和y值


如果有人能告诉我们如何正确初始化和访问表格,我们将不胜感激。

在函数
单元格:new
中,
self
是表格
单元格本身,因此您每次都返回相同的表格

一个简单的修复方法是创建一个新表:

function Cell:new(i, j)
    local t = {}

    t.x_min = (i-1) * CELL_SIZE 
    --omit the rest

    return t;
end
对于未来的改进,您可能会对实现原型的另一种方式感兴趣:

function Cell:new(i, j)
    local o = {}
    setmetatable(o, self)
    self.__index = self

    self.x_min = (i-1) * CELL_SIZE 
    --omits rest

    return o;
end

阅读以了解更多信息。

关于样式的注释:
单元格。选中了
而不是
单元格[“选中”]
,等等@inf感谢您的建议。这是使用该语言的第一天。您明白为什么代码只适用于右下角吗?它是否可以在可变范围内这样做?