[code] Global callbacks (cool!)

Discuss using and improving Lua and the Lua Player specific to the PSP.

Moderators: Shine, Insert_witty_name

Post Reply
Durante
Posts: 65
Joined: Sun Oct 02, 2005 6:07 am
Location: Austria

[code] Global callbacks (cool!)

Post by Durante »

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:

globalCallbacks.lua

Code: Select all

---- 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
You use it like this:

Code: Select all

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)

This is why I love dynamic languages.
Durante
Posts: 65
Joined: Sun Oct 02, 2005 6:07 am
Location: Austria

Post by Durante »

Here's an improved version that allows you to use Controls.read normally in the handlers without causing a stack overflow ;)

Code: Select all

---- 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.
chaos
Posts: 135
Joined: Sun Apr 10, 2005 5:05 pm

Post by chaos »

very nice idea..!
Chaosmachine Studios: High Quality Homebrew.
Post Reply