Love2d: Simple logger

If you've been working with Love2d, you might have noticed that there isn't an actual debug console, and print() calls will not get displayed anywhere.
However, it's pretty easy to make your own system to display single-line output messages.
Here is an example of one.

trace = {
	textl = { },
	stylel = { },
	styles = {
		white = { r = 255, g = 255, b = 255 },
		red = { r = 255, g = 127, b = 127 },
		green = { r = 191, g = 255, b = 127 },
		blue = { r = 127, g = 159, b = 255 },
		-- add your own style definitions here
		default = { r = 224, g = 224, b = 224 }
	},
	count = 0,
	limit = 32
}
function trace.print(text, style)
	if (style == nil) then -- no style given
		style = trace.styles.default
	end
	if (trace.count > trace.limit) then -- scroll elements
		table.remove(trace.textl, 1)
		table.remove(trace.stylel, 1)
	else -- add element
		trace.count = trace.count + 1
	end -- write data:
	trace.textl[trace.count] = text
	trace.stylel[trace.count] = style
end
function trace.draw(x, y)
	local i, s, z, prefix
	prefix = '' 
	-- default position parameters:
	if (x == nil) then x = 16 end
	if (y == nil) then y = 16 end
	-- draw lines:
	for i = 1, trace.count do
		s = trace.stylel[i]
		z = prefix .. trace.textl[i] -- string to draw
		-- choose white/black outline:
		if ((s.r < 160) and (s.g < 160) and (s.b < 160)) then
			love.graphics.setColor(255, 255, 255)
		else
			love.graphics.setColor(0, 0, 0)
		end
		-- draw outline:
		love.graphics.print(z, x + 1, y)
		love.graphics.print(z, x - 1, y)
		love.graphics.print(z, x, y + 1)
		love.graphics.print(z, x, y - 1)
		-- draw color:
		love.graphics.setColor(s.r, s.g, s.b)
		love.graphics.print(z, x, y)
		-- concatenate prefix:
		prefix = prefix .. '\n'
	end
end

So you get trace.print which adds a line of text to list, and trace.draw, which must be called when you need your messages to be drawn.
Below a sample implementation (seen on screenshot) follows:

require 'trace'
 
function love.mousepressed(x, y, b)
	trace.print('Mouse "' .. tostring(b) .. '" clicked at ('
		.. tostring(x) .. ', ' .. tostring(y) .. ')', trace.styles.green)
end
 
function love.keypressed(k)
	trace.print('Key pressed: ' .. tostring(k), trace.styles.red)
end
function love.keyreleased(k)
	trace.print('Key released: ' .. tostring(k), trace.styles.blue)
end
 
function love.draw()
	trace.draw()
end
 
function love.load()
	love.graphics.setBackgroundColor(63, 63, 63)
	trace.print('Trace system online.', trace.styles.green)
end

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.