Модул:Milokod

Извор: SI Wiki
Пређи на навигацију Пређи на претрагу

Документацију овог модула можете да направите на страници Модул:Milokod/док

local p = {}

require('strict')

local KEYWORDS = {
	-- Условни изрази
	['if'] = true,
	['then'] = true,
	['else'] = true,
	['end_if'] = true,
	-- Петље
	['for'] = true,
	['do'] = true,
	['end_for'] = true,
	['while'] = true,
	['end_while'] = true,
	['break'] = true,
	['repeat'] = true,
	['until'] = true,
	-- Опсези и низови
	['in'] = true,
	['to'] = true,
	-- Остало
	['return'] = true,
}

local OPERATORS = {
	['and'] = true,
	['or'] = true,
	['not'] = true,
	['nil'] = true
}

local function heading(highlighted, line)
	table.insert(highlighted, ' <u>')
	local paren = mw.ustring.find(line, '(', 0, true)
	if paren ~= nil then
		local funcname = mw.ustring.sub(line, 1, paren - 1)
		table.insert(highlighted, mw.ustring.upper(funcname))
		table.insert(highlighted, '(')
		local args = mw.ustring.sub(line, paren + 1, mw.ustring.len(line) - 1)
		for idx, arg in ipairs(mw.text.split(args, ',', true)) do
			table.insert(highlighted, '\'\'')
			table.insert(highlighted, mw.text.trim(arg))
			table.insert(highlighted, '\'\'')
			table.insert(highlighted, ', ')
		end
		-- Замена последње запете са затвореном заградом.
		highlighted[#highlighted] = ')'
	else
		table.insert(highlighted, line)
	end
	table.insert(highlighted, '</u>')
end

local function highlighter(varname)
	if KEYWORDS[varname] then
		return '\'\'\'' .. varname .. '\'\'\''
	elseif OPERATORS[varname] then
		return varname
	else
		return '\'\'' .. varname .. '\'\''
	end
end

local function body(line)
	local newline, _ = mw.ustring.gsub(line, '%f[%w_-][a-z0-9-_]+%f[^%w_-]', highlighter)
	newline, _ = mw.ustring.gsub(newline, '%f[%w_-][A-Z]%f[^%w_-]', highlighter)
	return newline
end

function p.main(frame)
	local milocode = mw.text.trim(mw.text.decode(mw.text.unstrip(frame:getParent().args[1])))
	local highlighted = {}
	for lineno, line in ipairs(mw.text.split(milocode, '\n', true)) do
		if lineno == 1 then
			heading(highlighted, line)
		else
			table.insert(highlighted, ' ')
			table.insert(highlighted, body(line))
		end
		table.insert(highlighted, '\n')
	end
	-- Уклања се последња празна линија.
	highlighted[#highlighted] = nil
	return table.concat(highlighted)
end

return p