Reputation: 1026
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.
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.
Upvotes: 0
Views: 417
Reputation: 14565
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
}
Upvotes: 0
Reputation: 26744
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. 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; in this case you get object
as implicitly declared self
variable (note that you call it a bit differently too):
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)
Upvotes: 1