怎样在Lua中用表格初始化表格?

我和一个朋友尝试使用Löve框架在Lua中编写扫雷游戏程序。到目前为止,代码需要检查一个方框(一个单元格)是否被选中并绘制它。我们对Lua很陌生,该程序现在存在一个缺陷,即它只适用于右下角的方框。

更新:现在看来,初始化的GameBoard的所有值都相同(即GameBoard [1]到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中相关的失败代码(在load方法中填充GameBoard的Cell时出错)。

--  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值。

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

点赞
用户1009479
用户1009479

Cell:new 函数中,self 是指 Cell 这个表本身,因此每次返回的都是同一个表。

一个简单的解决方法是创建一个新的表:

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

    t.x_min = (i-1) * CELL_SIZE
    --省略其余

    return t;
end

对于未来的改进,你可能会对另一种实现原型的方法感兴趣:

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

    self.x_min = (i-1) * CELL_SIZE
    --省略其余

    return o;
end

阅读《PiL: 面向对象编程》以获取更多信息。

2014-11-01 05:01:04