怎样在Lua中用表格初始化表格?
2014-11-1 5:3:3
收藏:0
阅读:115
评论:1
我和一个朋友尝试使用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值。
如果有人能告诉我们如何正确初始化和访问表格,我们将不胜感激。
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
在
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: 面向对象编程》以获取更多信息。