gpt4 book ai didi

lua - 如何在 Lua 中用表初始化表?

转载 作者:行者123 更新时间:2023-12-01 23:50:46 24 4
gpt4 key购买 nike

我和一个 friend 尝试使用 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 以来的最新值)。表 ( Cells ) 的所有元素 ( Gameboard ) 都具有在 Cell:new 中设置的相同 x 和 y 值方法。

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

最佳答案

在函数 Cell:new 中,self 是表 Cell 本身,所以你每次都返回同一个表。

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

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

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

return t;
end

为了将来的改进,您可能对另一种实现原型(prototype)的方式感兴趣:

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了解更多信息。

关于lua - 如何在 Lua 中用表初始化表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26685409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com