gpt4 book ai didi

lua - 尝试使用电晕为属于 lua 数组一部分的对象添加事件监听器

转载 作者:行者123 更新时间:2023-12-04 05:38:52 25 4
gpt4 key购买 nike

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 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))

最佳答案

这让我难倒直到今天。主要问题是您将 newdice 设为 Corona display.newText 对象,然后将其重新分配为骰子对象。所有 Corona 对象都像普通 table 一样,但它们实际上是特殊对象。所以你有两个选择:

A. 不要使用类和 OOP。就像你现在的代码一样,没有理由让骰子成为一个类。这是我会选择的选项,除非你有一些令人信服的理由让骰子成为一个类(class)。以下是您将如何实现此选项

--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 是一个局部变量,所以它不是你的骰子类的成员。

关于lua - 尝试使用电晕为属于 lua 数组一部分的对象添加事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11550311/

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