I wanted to be able to make screenshots and do some debugging stuff from anywhere in my program without cluttering up my UI/game loop code, so I came up with this:
---- An object implementing global key functions ----
-------------------------------------------------------------------------------
GlobalCallbacks = {
funcs = {},
ctrlread = Controls.read
}
function GlobalCallbacks:register(f)
table.insert(self.funcs, f)
end
function GlobalCallbacks:remove(f)
for i, v in pairs(self.funcs) do
if v == f then
table.remove(self.funcs, i)
end
end
end
function GlobalCallbacks:read()
local ctrl = self.ctrlread()
for _, v in pairs(self.funcs) do
v(ctrl)
end
return ctrl
end
Controls.read = function()
return GlobalCallbacks:read()
end
dofile("src/globalcallbacks.lua")
GlobalCallbacks:register(function(ctrl)
if ctrl:select() then
screen:save("screenshot.png")
end
end)
Simple, but effective. (i.e. with the above code you can now make a screenshot by pressing select, EVERYWHERE controls are read)
---- An object implementing global key functions ----
-------------------------------------------------------------------------------
GlobalCallbacks = {
funcs = {},
ctrlread = Controls.read,
fakeread = nil
}
function GlobalCallbacks:register(f)
table.insert(self.funcs, f)
end
function GlobalCallbacks:remove(f)
for i, v in pairs(self.funcs) do
if v == f then
table.remove(self.funcs, i)
end
end
end
function GlobalCallbacks:clear()
self.funcs = {}
end
function GlobalCallbacks:read()
local ctrl = self.ctrlread()
Controls.read = self.ctrlread
for _, v in pairs(self.funcs) do
v(ctrl)
end
Controls.read = self.fakeread
return ctrl
end
function GlobalCallbacks:cleanup()
Controls.read = self.ctrlread
end
GlobalCallbacks.fakeread = function()
return GlobalCallbacks:read()
end
Controls.read = GlobalCallbacks.fakeread
You should call GlobalCallbacks:cleanup() before exiting if you want your program to play nicely with other Lua stuff launched in the same session.