我有以下代码:
{
identifier = "hand:" .. card.name,
area = { x, y, 100, 100 },
on_click = function()
-- Code goes here
end
}
我想使用card变量和对放置此代码的对象的引用来修改类的变量,其值为card
变量。
那么,如何将本地上下文中的参数提供给将在其他代码段中调用的函数?
我希望在事件管理循环中启动on_click
函数。
答案 0 :(得分:1)
如果我正确理解了这个问题,你希望能够从on_click处理程序引用on_click
处理程序所属的对象。为此,您需要拆分您拥有的语句:
local card = { name = "my card" }
local object = {
identifier = "hand:" .. card.name,
area = { x, y, 100, 100 },
}
object.on_click = function()
-- Code goes here
-- you can reference card and object here (they are upvalues in this context)
print(card.name, object.area[3])
end
object.click()
您也可以稍微定义on_click
;在这种情况下,您将object
视为隐式声明的self
变量(请注意,您也称它为有点不同):
function object:on_click()
-- Code goes here
-- you can reference card and object here
print(card.name, self.area[3])
end
object:click() -- this is the same as object.click(object)
答案 1 :(得分:0)
在分配功能时保存它,如此
{
identifier = "hand:" .. card.name,
area = { x, y, 100, 100 },
on_click = function()
local a_card = card
print(a_card.name)
end
}