Jump to content

Module:Boolean

From Wikipedia, the free encyclopedia

local p = {}
local makeInvokeFunc = require("Module:MakeInvokeFunc")

local function notEmpty(t)
	return (t ~= nil and t ~= "" and t ~= 0 and t ~= false)
end


p._and = function(args)
	local allTrue = true
	local top = tonumber(args['n']) or 2
	for i = 1, top do
		if args[i] == nil then args[i] = false end
		allTrue = allTrue and notEmpty(args[i])
	end
	if allTrue then return args['true'] or 'true' end
	return args['false'] or ''
end

p._or = function(args)
	local oneTrue = false
	local top = tonumber(args['n']) or 2
	for i = 1, top do
		if args[i] == nil then args[i] = false end
		oneTrue = oneTrue or notEmpty(args[i])
	end
	if oneTrue then return args['true'] or 'true' end
	return args['false'] or ''
end

p._not = function(args)
	if not notEmpty(args[1]) then return args['true'] or 'true' end
	return args['false'] or ''
end

p._xor = function(args)
	local xorResult = false
	local top = tonumber(args['n']) or 2
	for i = 1, top do
		if args[i] == nil then args[i] = false end
		xorResult = xorResult ~= notEmpty(args[i])
	end
	if xorResult then return args['true'] or 'true' end
	return args['false'] or ''
end

p._nand = function(args)
	local args2 = {}
	for k,v in pairs(args) do
		if (tonumber(k) ~= nil) then
			args2[tonumber(k)] = v
		end
	end
	mw.logObject(args2)
	return p._not({ p._and({ args2[1], args2[2] }), ['true'] = args['true'], ['false'] = args['false'] })
end

p._nor = function(args)
	local args2 = {}
	for k,v in pairs(args) do
		if (tonumber(k) ~= nil) then
			args2[tonumber(k)] = v
		end
	end
	mw.logObject(args2)
	return p._not({ p._or(args2), ['true'] = args['true'], ['false'] = args['false'] })
end

p._xnor = function(args)
	local args2 = {}
	for k,v in pairs(args) do
		if (tonumber(k) ~= nil) then
			args2[tonumber(k)] = v
		end
	end
	mw.logObject(args2)
	return p._not({ p._xor(args2), ['true'] = args['true'], ['false'] = args['false'] })
end

p._main = function(args)
	local args2 = {}
	for k,v in pairs(args) do
		if tonumber(k) ~= nil then
			if tonumber(k) ~= 1 then
				args2[tonumber(k) - 1] = v
			end
		end
	end
	args2['true'] = args['true']
	args2['false'] = args['false']
	return p["_" .. args[1]](args2)
end

p["and"] = makeInvokeFunc(p)("_and")
p.AND = p["and"]
p["&&"] = p["and"]
p["or"] = makeInvokeFunc(p)("_or")
p.OR = p["or"]
p["||"] = p["or"]
p["not"] = makeInvokeFunc(p)("_not")
p.NOT = p["not"]
p["!"] = p["not"]
p["xor"] = makeInvokeFunc(p)("_xor")
p.XOR = p["xor"]
p["^^"] = p["xor"]
p["nand"] = makeInvokeFunc(p)("_nand")
p.NAND = p["nand"]
p["nor"] = makeInvokeFunc(p)("_nor")
p.NOR = p["nor"]
p["xnor"] = makeInvokeFunc(p)("_xnor")
p.XNOR = p["xnor"]
p["main"] = makeInvokeFunc(p)("_main")

return p