Skip to content

Useful debugging functions

BAD-AL edited this page Feb 12, 2021 · 1 revision
-- for table/object printing
if( dumpToString == nil ) then 
	function dumpToString(obj, count)
		if( count == nil ) then count = 0 end 
		if type(obj) == 'table' then
			local retVal =  string.rep('  ', count) .. '{ '
			for k,v in pairs(obj) do
				retVal =  retVal ..  tostring(k) .. ':' .. dumpToString(v, count+1) .. ', '
			end
			return retVal .. ' },'
		elseif type(obj) == 'string' then 
			return '"' ..  tostring(obj) .. '"'
		else 
			return tostring(obj) 
		end
	end
end 

if( printf == nil ) then 
	function printf(...)
		print(string.format( unpack(arg) ))
	end 
end 

-- intercept 'print' statements and put them in the credits so we can see them on console.
if( oldPrint == nil ) then 
	oldPrint = print

	function ResetDebugLog()
		debugLog = { "Debug log:" }
	end 
	
	ResetDebugLog() -- create our debug log for print stuff to go to 

	print = function (...)
		if( table.getn(arg) > 0 ) then 
			local count = table.getn(debugLog)
			debugLog[count+1] = arg[1]
		end
		oldPrint(unpack(arg))
	end 
end 

if ( SetDebugStuffOnCredits == nil ) then 
	function SetDebugStuffOnCredits( listOfStrings )
		local numberOfStrings = table.getn(listOfStrings)
		local numCredits = table.getn(CreditLines)
		local debugStringIndex = 1
		local creditIndex = 1
		
		--print("SetDebugStuffOnCredits numCredits:" .. numCredits .. " numberOfStrings: " .. numberOfStrings )
			
		while ( debugStringIndex <= numberOfStrings and creditIndex <= numCredits ) do 
			if( CreditLines[creditIndex]["str"] ~= nil ) then 
				CreditLines[creditIndex]["str"] = listOfStrings[debugStringIndex]
				debugStringIndex = debugStringIndex +1
			end 
			creditIndex = creditIndex + 1
		end 
	end 
end 


function PrintGlobalStringsContaining(keyword )
	-- logic to gather the data / debug strings 
	print("Global variables that have '" .. keyword ..  "' in them: " )
	local location = nil 
	local lowercase_key = ""
	keyword = string.lower( keyword )
	for k,v in pairs(_G) do
		lowercase_key = string.lower(k)
		location = string.find(lowercase_key, keyword) 
		if (location ~= nil  ) then 
			print( k ) -- we've redefined 'print' to add to our debug strings 
		end
	end 
end