Passing a 'self' function as a parameter
Posted: Thu Nov 07, 2019 6:28 am
I'm not really sure how to word this properly, but what I want to do is pass a function that requires the self argument to another outside function. Say I have a Button object:
And then I want to tie a button to a custom Square object:
How would I pass the "square:increment()" function into the "newButton()" function as a parameter? Sorry if this is confusing, I'm still trying to wrap my head around coding. Any help would be greatly appreciated!
Code: Select all
local button = {}
button.__index = button
function newButton(f)
return setmetatable({function = f}, button)
end
function button:update(dt)
-- Assume clicked() is a pre-written function.
if clicked(self) then self.function() end
end
Code: Select all
local square = {}
square.__index = square
function newSquare(f)
return setmetatable({n = 0, button = newButton(?)}, square)
end
function square:increment()
self.n = self.n + 1
end