[英]how to give parameters to closure in lua
I have the following code : 我有以下代码:
{
identifier = "hand:" .. card.name,
area = { x, y, 100, 100 },
on_click = function()
-- Code goes here
end
}
I want to use the card variable and a reference to the object where this code is placed to modify a variable of the class with a value of the card
variable. 欲使用该卡和变量到该代码被放置到修改类的变量与所述的值的对象的引用
card
变量。
So, how can I give parameters from the local context to the function who will be called in other pieces of code ? 因此,如何将局部上下文中的参数提供给将在其他代码段中调用的函数?
I wish to launch the on_click
function in an event management loop. 我希望在事件管理循环中启动
on_click
函数。
If I understand the question correctly, you want to be able to reference from on_click handler the object that on_click
handler belongs to. 如果我理解正确的问题,你希望能够从on_click处理程序来引用该对象
on_click
处理器属于。 To do this, you need to split the statement you have: 为此,您需要拆分以下语句:
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()
You can also define on_click
a bit differently; 您也可以对
on_click
进行一些不同的定义。 in this case you get object
as implicitly declared self
variable (note that you call it a bit differently too): 在这种情况下,您将
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)
save it when you assign the function, like this 分配功能时将其保存,就像这样
{
identifier = "hand:" .. card.name,
area = { x, y, 100, 100 },
on_click = function()
local a_card = card
print(a_card.name)
end
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.