如何在Lua中使用表来初始化表?

3
我和一位朋友正在尝试使用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 中相关失败的代码(在加载方法中填充 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值。
如果有人能告诉我们如何正确地初始化和访问一个表格,那将不胜感激。

关于代码风格的注释:使用 cell.checked 而不是 cell["checked"] 等等。 - lhf
@inf 感谢您的建议。这是学习该语言的第一天。您是否明白为什么代码只适用于右下角?这可能与变量作用域有关吗? - user2609980
1个回答

3
在函数Cell:new中,self指的是表格Cell本身,因此每次返回的都是同一个表格。
一个简单的解决方法是创建一个新的表格:
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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接