Module:Sandbox/Johnuniq/debug

From WikiProjectMed
Jump to navigation Jump to search
--[=[ Module:Sandbox/Johnuniq/debug

-- Whatever is pasted in the debug console is interpreted as a single command.
-- That means you cannot paste, say, two lines where each is a command.

-- In the debug console, can get the current frame and pass it to main.
-- Setting args has no effect.
f = mw.getCurrentFrame()
f.args[1] = 'Ignored'
f.args[2] = 42
=mw.logObject(f, 'f')
=p.main(f)

-- Can create a child frame with specified args.
f2 = f:newChild({title='MyTitle', args={120,94321,name='hello','{{convert|12|kg}}'}})
f3 = mw.getCurrentFrame():newChild({title='MyTitle', args={120,94321,name='hello','{{convert|12|kg}}'}})
=mw.logObject(f2, 'f2')
=p.main(f2)
=p.main(f3)

-- If main uses Module:Arguments, can pass a table to main.
-- That means argument values may be any data type (normally, arguments are strings).
-- main gets a table, not a frame, so methods like frame:getTitle() cannot be used.
=p.mainargs({11, 22, name='hello', 'more', number=420})

-- See talk for examples of displaying a table.

]=]

local function spell(number)
	local names = {[0] = 'Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'}
	if number >= 200 then
		mw.log('number = ' .. number)
		mw.logObject(names, 'names')
	end
	local digits = ''
	repeat
		local unit = number % 10
		number = math.floor(number / 10)
		digits = names[unit] .. digits
	until number == 0
	return digits
end

local function listArgs(frame, args)
	local results, n = {}, 0
	local function add(k, v)
		n = n + 1
		if type(k) == 'string' then
			k = '"' .. k .. '"'
		end
		results[n] = 'parameter ' .. tostring(k) .. ', value ' .. tostring(v)
	end
	for k, v in pairs(args) do
		add(k, v)
		if tonumber(v) then
			add('...spelled', spell(tonumber(v)))
		elseif type(v) == 'string' and v:sub(1, 2) == '{{' then
			add('...expanded', frame:preprocess(v))
		end
	end
	local extra = frame.getTitle and ('Title ' .. frame:getTitle()) or '(not frame)'
	return extra .. '\n' .. table.concat(results, '\n')
end

local function main(frame)
	return listArgs(frame, frame.args)
end

local function mainargs(frame)
	local args = require('Module:Arguments').getArgs(frame)
	return listArgs(frame, args)
end

local function dump(frame)
	local testcase = require('Module:Dump').testcase('return table')
	mw.logObject(testcase)  -- result can be seen when previewing an edit of a page calling this function
	return mw.dumpObject(testcase)
end

return {
	main = main,
	mainargs = mainargs,
	dump = dump,
}