Module:Sandbox

From Wikisource
Jump to navigation Jump to search
Documentation icon Module documentation[create]
local z = {}

-- Generate random number
function z.randomseed(frame)
    seed = tonumber(frame.args[1]) or tonumber(tostring(os.time()):reverse():sub(1,6))
	math.randomseed(seed)
	return
end

function z.random( frame )
    first = tonumber(frame.args[1]) -- if it doesn't exist it's NaN, if not a number it's nil
    second = tonumber(frame.args[2])

    if first then -- if NaN or nil, will skip down to final return
        if second and first <= second then -- could match if both nil, but already checked that first is a number in last line
            return math.random(first, second)
        end
        return math.random(first)
    end   
    return math.random()
end

function z.randomset(frame)
    max = tonumber(frame.args[1]) -- if it doesn't exist it's NaN, if not a number it's nil
    count = tonumber(frame.args[2])

	if not (max or count) then return '<strong class="error">Error: not enough arguments provided</strong>' end
	if max < count then return '<strong class="error">Error: there are not enough unique integers in the range</strong>' end
	a = {}
    r = ""
    for i=1, max do
      a[i] = i
    end
   	r = table.remove(a, math.random(max))
    for i=1, count-1 do
    	r = r .. "," .. table.remove(a, math.random(max-i))
	end
	return r
end

return z