【问题标题】:How to initialize a table with tables in Lua?如何用 Lua 中的表初始化表?
【发布时间】:2014-12-28 09:46:34
【问题描述】:

我和一个朋友尝试使用 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填充Cells的加载方法中出错。

--  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"]
  • @inf 感谢您的建议。这是语言的第一天。你明白为什么代码只适用于右下角吗?它可以与变量范围有关吗?

标签: lua lua-table love2d minesweeper


【解决方案1】:

在函数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: Object-Oriented Programming了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2015-04-17
    相关资源
    最近更新 更多