正在尝试使用corona为作为lua中数组一部分的对象添加事件侦听器
main将创建一个简单的二维阵列。现在我想为表中的每个对象创建一个addeventlistener。我想我是在课堂上这样做的吧?虽然我创建了一个taps函数,然后定义了addeventlistener,但是我发现了一些错误正在尝试使用corona为作为lua中数组一部分的对象添加事件侦听器,lua,coronasdk,Lua,Coronasdk,main将创建一个简单的二维阵列。现在我想为表中的每个对象创建一个addeventlistener。我想我是在课堂上这样做的吧?虽然我创建了一个taps函数,然后定义了addeventlistener,但是我发现了一些错误 --main.lua-- grid={} for i =1,5 do grid[i]= {} for j =1,5 do grid[i][j]=diceClass.new( ((i+2)/10),((j+2)/10)) end end --dice
--main.lua--
grid={}
for i =1,5 do
grid[i]= {}
for j =1,5 do
grid[i][j]=diceClass.new( ((i+2)/10),((j+2)/10))
end
end
--dice class--
local dice = {}
local dice_mt = { __index = dice } -- metatable
function dice.new( posx, posy) -- constructor
local a=math.random(1,6)
local b= true
local newdice = display.newText(a, display.contentWidth*posx,
display.contentHeight*posy, nil, 60)
--newdice:addEventListener("tap", taps(event))
return setmetatable( newdice, dice_mt )
end
function dice:taps(event)
self.b = false
print("works")
end
function dice:addEventListener("tap", taps(event))
删除最后一行
addEventListener函数的调用方式如下
newdice:addEventListener("tap", taps)
这件事一直困扰着我,直到今天。主要问题是您正在将newdice设置为Corona display.newText对象,然后将其重新指定为dice对象。所有的电晕对象都像普通的桌子,但它们实际上是特殊的对象。所以你有两个选择: 不要使用类和OOP。正如您现在的代码一样,没有理由让dice成为一个类。除非你有令人信服的理由让骰子成为一门课,否则我会选择这个选项。下面是您将如何实现此选项
--dice not a class--
local dice = {}
local function taps(event)
event.target.b = false
print("works")
end
function dice.new( posx, posy) -- constructor
local a=math.random(1,6)
--local b= true
local newdice = {}
newdice = display.newText(a, display.contentWidth*posx,
display.contentHeight*posy, nil, 60)
newdice:addEventListener("tap", taps)
newdice.b = true
return newdice
end
或B.对显示对象使用“has a”关系而不是“is a”关系。因为不能使它们同时成为骰子对象和显示对象,所以骰子对象可以包含显示对象。下面是它的样子
--dice class--
local dice = {}
local dice_mt = { __index = dice } -- metatable
local function taps(event)
event.target.b = false
print("works")
end
function dice.new( posx, posy) -- constructor
local a=math.random(1,6)
--local b= true
local newdice = {}
newdice.image = display.newText(a, display.contentWidth*posx,
display.contentHeight*posy, nil, 60)
newdice.image:addEventListener("tap", taps)
newdice.b = true
return setmetatable( newdice, dice_mt )
end
还有其他一些问题。在taps函数事件处理程序中,必须使用event.target.b而不是self.b。此外,在dice中,new b是一个局部变量,因此它不是dice类的成员。始终提供您得到的确切错误消息:它帮助那些能够更好地帮助您的人。这意味着您尚未定义taps函数。在addEventListener callin main.lua之前的某个地方编写taps函数。我使用:grid[i][j]。image:addEventListener(“tap”,dicetap),并在前面声明dicetap fn。