Module:Debug

From Melvor Idle

Documentation for this module may be created at Module:Debug/doc

-- Helper module to debug and test Lua code.
local p = {}

local SB = require('Module:StringBuilder')

-- Local variables used to local functions
local nesting = 0
local sb = nil
local isParentObject = false

-- Adds an indent to the stringbuilder, depending on the current nest count.
local function appendIndent()
	for i = 1, nesting do
		sb:append('    ')
	end
end

-- Forward declare local functions
local logObject
local logTable

-- Converts objects to a string representation
logObject = function(obj)
	if type(obj) == 'table' then
		-- Applies indenting only if this isn't the topmost element.
		if isParentObject == true then
			isParentObject = false
		else
			nesting = nesting + 1
			sb:appendLine()
		end
		
		logTable(obj)
		nesting = nesting - 1
		appendIndent()
	else
		sb:append(tostring(obj))
	end
end

-- Converts a table to its string representation
logTable = function(tbl)
	for key, value in pairs(tbl) do
		appendIndent()
		sb:append('[')
		if key then
			logObject(key)
			sb:append(', ')
		end
		
		logObject(value)
		sb:appendLine(']')
	end
end

-- Logs an object to the debug console
function p.log(obj)
	mw.log(p.toString(obj))
end

-- Converts any object to a string representation.
function p.toString(obj)
	-- Reset all local variables.
	sb = SB.new()
	nesting = 0
	isParentObject = true
	
	-- Log object to local stringbuilder
	logObject(obj)
	
	return sb:toString()
end

return p