[SOLVED] Dynamically create methods for a class.
Posted: Sat Jun 08, 2019 11:15 am
I am trying to hook a number of love handlers to a class. All they have to do is to propagate the call to all of the children. Although there are so many handlers I decided to list them all to a table then attempt to generate them through a for loop.
The code shown below is what I described above.
Is it possible in the first place? If so, what am I doing wrong?
Because this works
But this doesn't
Notes
The code shown below is what I described above.
Code: Select all
local callbacks = {
"update", "keypressed", "keyreleased", "textedited", "textinput",
"mousemoved", "mousepressed", "mousereleased", "wheelmoved",
"gamepadaxis", "gamepadpressed", "gamepadreleased", "joystickadded",
"joystickaxis", "joystickhat", "joystickpressed", "joystickreleased",
"joystickremoved", "touchmoved", "touchpressed", "touchreleased"
}
for _, v in ipairs(callbacks) do
local func = function(...)
local args = {...}
self.children:forEach(function(i, child)
if type(child[v]) == "function" then
child[v](unpack(args))
end
end)
end
self.class.__declaredMethods[v] = func
self.class.__instanceDict[v] = func
Because this works
Code: Select all
self.update = function(dt)
print "Hello World"
end
Code: Select all
function Game:update(dt)
print "Hello World"
end
- I'm also using kikito's middleclass for OOP.
- self.Children is a class similar to C#'s List.
- Although I can use love.handlers, I decided to list only input handlers.