Jump to content
Wikipedia The Free Encyclopedia

Module:Random

From Wikipedia, the free encyclopedia
Module documentation[view] [edit] [history] [purge]
Warning This Lua module is used on approximately 13,000 pages and changes may be widely noticed. Test changes in the module's /sandbox or /testcases subpages, or in your own module sandbox. Consider discussing changes on the talk page before implementing them.
This module is rated as ready for general use. It has reached a mature state, is considered relatively stable and bug-free, and may be used wherever appropriate. It can be mentioned on help pages and other Wikipedia resources as an option for new users. To minimise server load and avoid disruptive output, improvements should be developed through sandbox testing rather than repeated trial-and-error editing.
Page template-protected This module is currently protected from editing.
See the protection policy and protection log for more details. Please discuss any changes on the talk page; you may submit an edit request to ask an administrator to make an edit if it is uncontroversial or supported by consensus. You may also request that this page be unprotected.
This module depends on the following other modules:

This module contains a number of functions that use random numbers. It can output random numbers, select a random item from a list, and reorder lists randomly. The randomly reordered lists can be output inline, or as various types of ordered and unordered lists. The available functions are outlined in more detail below.

Number

The number function outputs a random number.

{{#invoke:random|number|m|n|same=yes}}

The arguments m and n may be omitted, but if specified must be convertible to integers.

  • With no arguments, returns a real number in the range [ 0 , 1 ) {\displaystyle [0,1)} {\displaystyle [0,1)}.
  • With one argument, returns an integer in the range [ 1 , m ] {\displaystyle [1,m]} {\displaystyle [1,m]}, or, if m is negative, ( m , 0 ] {\displaystyle (-m,0]} {\displaystyle (-m,0]}. If m is equal to 0 or 1, returns 1 (or 0 if m = 1 {\displaystyle m=-1} {\displaystyle m=-1}).
  • With two arguments, returns an integer in the range [ m , n ] {\displaystyle [m,n]} {\displaystyle [m,n]}. m and n can be either positive or negative. If m is greater than n, returns an integer in the range [ n , m ] {\displaystyle [n,m]} {\displaystyle [n,m]} instead.
  • If the |same= parameter is set to "yes", "y", "true", or "1", the same random number is returned for each module call on a given page.

Examples (refresh )

  • {{#invoke:random|number}} → 0.91234088545308
  • {{#invoke:random|number|100}} → 53
  • {{#invoke:random|number|-100|-50}} → -95
  • {{#invoke:random|number|100|same=yes}} → 2
  • {{#invoke:random|number|100|same=yes}} → 2

The documentation for this function is partly taken from the Scribunto Lua reference manual, which is in turn based on the Lua 5.1 Reference Manual, available under the MIT License.

Date

The date function outputs a random date.

{{#invoke:random|date|timestamp1|timestamp2|format=date format|same=yes}}
  • If no timestamp arguments are specified, the module outputs a random date in the current year.
  • If timestamp1 and timestamp2 are specified, the module outputs a random date between the two timestamps. timestamp1 must be earlier than timestamp2.
  • If only timestamp1is specified, the module outputs a random date between the Unix epoch (1 Jan 1970) and the timestamp. timestamp1 must not be earlier than 1 Jan 1970.
  • Formatting can be specified with the |format= parameter. The default formatting is "hh:mm, DD Month YYYY (UTC)" (the same as the default Wikipedia timestamp).
  • The timestamps and the |format= parameter accept values compatible with the #time parser function. Please see the #time documentation for the full range of possible input values and formatting options.
  • If the |same= parameter is set to "yes", "y", "true", or "1", the same date is returned for each module call on a given page.

Examples (refresh )

  • {{#invoke:random|date}} → 03:43, 19 April 2025 (UTC)
  • {{#invoke:random|date|format=F j}} → March 21
  • {{#invoke:random|date|1 Jan 1980|31 Dec 1999}} → 16:31, 15 May 1992 (UTC)
  • {{#invoke:random|date|1st January 1500|1st January 3000|format=g:i a, l d M Y}} → 8:50 am, Saturday 19 Jul 2369
  • {{#invoke:random|date|1970年06月01日}} → 13:52, 13 January 1970 (UTC)
  • {{#invoke:random|date|same=yes}} → 18:47, 07 January 2025 (UTC)
  • {{#invoke:random|date|same=yes}} → 18:47, 07 January 2025 (UTC)

Item

The item function outputs a random item from a list.

{{#invoke:random|item|list item 1|list item 2|list item 3|...|same=yes}}

If the |same= parameter is set to "yes", "y", "true", or "1", the same item is returned for each module call on a given page.

Example (refresh )

  • {{#invoke:random|item|egg|beans|sausage|bacon|spam}} → egg
  • {{#invoke:random|item|egg|beans|sausage|bacon|spam|same=yes}} → sausage
  • {{#invoke:random|item|egg|beans|sausage|bacon|spam|same=yes}} → sausage

Setting "same" will make the template select the same number item from each list, even if the things in them are different.

  • My
    {{#invoke:random|item|egg |bean |sausage |bacon |spam |same=yes}}
    is
    {{#invoke:random|item|quail |pinto |kielbasa |canadian |spammy|same=yes}}
    and my
    {{#invoke:random|item|blegg |blean |blausage |blacon |blam |same=yes}}
    is
    {{#invoke:random|item|blail |blinto|blielbasa|blanadian|blammy|same=yes}}
    

→ My sausage is kielbasa and my blausage is blielbasa.

List

The list function outputs a list in a random order.

{{#invoke:random|list|list item 1|list item 2|list item 3|...|sep=separator|limit=number of items to display|same=yes}}

Named parameters

  • |sep= or |separator= - an optional separator for the list items. Some values are special; see the table below.
  • |limit= - the maximum number of list items to display. The lowest possible is 0 and the highest possible is the length of the list.
  • |same= - if this is set to "yes", "y", "true", or "1", the list order is the same for each module call on a given page.
Possible separator values
Code Output
dot  ·
pipe |
comma ,
tpt-languages ⧼tpt-languages-separator⧽
space a space
newline a newline character
any other value other values are used without modification

You cannot input spaces directly to the |sep= parameter due to limitations in MediaWiki's template syntax. However, it is possible to work around this by using HTML entities. You can use   to represent a normal space, and   to represent a non-breaking space.

Examples (refresh )

  • {{#invoke:random|list|egg|beans|sausage|bacon|spam}} → baconsausagespambeansegg
  • {{#invoke:random|list|egg|beans|sausage|bacon|spam|sep=dot}} → beans · spam · sausage · bacon · egg
  • {{#invoke:random|list|egg|beans|sausage|bacon|spam|sep=space}} → bacon egg beans spam sausage
  • {{#invoke:random|list|egg|beans|sausage|bacon|spam|sep=; }} → beans; spam; bacon; sausage; egg
  • {{#invoke:random|list|egg|beans|sausage|bacon|spam|sep=foo}} → sausagefoospamfooeggfoobaconfoobeans
  • {{#invoke:random|list|egg|beans|sausage|bacon|spam|limit=3}} → sausageeggbeans
  • {{#invoke:random|list|egg|beans|sausage|bacon|spam|same=yes}} → baconbeansspameggsausage
  • {{#invoke:random|list|egg|beans|sausage|bacon|spam|same=yes}} → baconbeansspameggsausage

Text list

The text_list function outputs a list in a random order, text-style. In other words, it is like the list function, but with a different separator before the last item.

{{#invoke:random|text_list|list item 1|list item 2|list item 3|...|sep=separator|conj=conjunction|limit=number of items to display|same=yes}}

The separator can be specified with either the |sep= or |separator= parameters; its default value is ", ". The conjunction can be specified with either the |conj= or |conjunction= parameters; its default value is " and ". The separator and the conjunction can be specified with the same values as the separator in the list function.

The maximum number of list items to display can be set with the |limit= parameter. The lowest possible is 0 and the highest possible is the length of the list.

If the |same= parameter is set to "yes", "y", "true", or "1", the list order is the same for each module call on a given page.

Examples (refresh )

  • {{#invoke:random|text_list|egg|beans|sausage|bacon|spam}} → egg, spam, sausage, beans and bacon
  • {{#invoke:random|text_list|egg|beans|sausage|bacon|spam|sep=; }} → egg; beans; spam; sausage and bacon
  • {{#invoke:random|text_list|egg|beans|sausage|bacon|spam|sep=; |conj= or }} → sausage; spam; beans; egg or bacon
  • {{#invoke:random|text_list|egg|beans|sausage|bacon|spam|limit=3}} → beans, spam and egg
  • {{#invoke:random|text_list|egg|beans|sausage|bacon|spam|same=yes}} → bacon, beans, spam, egg and sausage
  • {{#invoke:random|text_list|egg|beans|sausage|bacon|spam|same=yes}} → bacon, beans, spam, egg and sausage

HTML lists

If you wish to output an HTML list in a random order, you can choose between five different functions: bulleted_list, unbulleted_list, horizontal_list, ordered_list, and horizontal_ordered_list. These functions all use Module:List.

Function name Produces Example code Example output (refresh )
bulleted_list Bulleted lists {{#invoke:random|bulleted_list|egg|sausage|spam}}
  • egg
  • sausage
  • spam
unbulleted_list Unbulleted lists {{#invoke:random|unbulleted_list|egg|sausage|spam}}
  • egg
  • sausage
  • spam
horizontal_list Horizontal bulleted lists {{#invoke:random|horizontal_list|egg|sausage|spam}}
  • egg
  • sausage
  • spam
ordered_list Ordered lists (numbered lists and alphabetical lists) {{#invoke:random|ordered_list|egg|sausage|spam}}
  1. egg
  2. sausage
  3. spam
horizontal_ordered_list Horizontal ordered lists {{#invoke:random|horizontal_ordered_list|egg|sausage|spam}}
  1. egg
  2. spam
  3. sausage
Basic usage
{{#invoke:random|function|list item 1|list item 2|list item 3|...|limit=number of items to display|same=yes}}
All parameters
{{#invoke:random|function
|first item|second item|third item|...
|start = start number for ordered lists
|type = type of marker for ordered lists
|list_style_type = type of marker for ordered lists (uses CSS)
|class = class
|style = style
|list_style = style for the list
|item_style = style for all list items
|item_style1 = style for the first list item |item_style2 = style for the second list item |...
|indent = indent for horizontal lists
}}

The maximum number of list items to display can be set with the |limit= parameter. The lowest possible is 0 and the highest possible is the length of the list.

If the |same= parameter is set to "yes", "y", "true", or "1", the list order is the same for each module call on a given page.

Please see Module:List for a full explanation of the other parameters.

The above documentation is transcluded from Module:Random/doc. (edit | history)
Editors can experiment in this module's sandbox (edit | diff) and testcases (edit) pages.
Subpages of this module.

 -- This module contains a number of functions that make use of random numbers.

 localcfg={}

 --------------------------------------------------------------------------------------
 -- Configuration
 --------------------------------------------------------------------------------------

 -- Set this to true if your wiki has a traffic rate of less than one edit every two minutes or so.
 -- This will prevent the same "random" number being generated many times in a row until a new edit is made
 -- to the wiki. This setting is only relevant if the |same= parameter is set.
 cfg.lowTraffic=false

 -- If cfg.lowTraffic is set to true, and the |same= parameter is set, this value is used for the refresh rate of the random seed.
 -- This is the number of seconds until the seed is changed. Getting this right is tricky. If you set it too high, the same number
 -- will be returned many times in a row. If you set it too low, you may get different random numbers appearing on the same page,
 -- particularly for pages that take many seconds to process.
 cfg.seedRefreshRate=60

 --------------------------------------------------------------------------------------
 -- End configuration
 --------------------------------------------------------------------------------------

 localp={}-- For functions available from other Lua modules.
 locall={}-- For functions not available from other Lua modules, but that need to be accessed using table keys.

 localyesno=require('Module:Yesno')
 localmakeList=require('Module:List').makeList

 --------------------------------------------------------------------------------------
 -- Helper functions
 --------------------------------------------------------------------------------------

 localfunctionraiseError(msg)
 -- This helps to generate a wikitext error. It is the calling function's responsibility as to how to include it in the output.
 returnmw.ustring.format('<b class="error">[[Module:Random]] error: %s.</b>',msg)
 end

 --------------------------------------------------------------------------------------
 -- random number function
 --------------------------------------------------------------------------------------

 localfunctiongetBigRandom(l,u)
 -- Gets a random integer between l and u, and is not limited to RAND_MAX.
 localr=0
 localn=2^math.random(30)-- Any power of 2.
 locallimit=math.ceil(53/(math.log(n)/math.log(2)))
 fori=1,limitdo
 r=r+math.random(0,n-1)/(n^i)
 end
 returnmath.floor(r*(u-l+1))+l
 end

 functionl.number(args)
 -- Gets a random number.
 first=tonumber(args[1])
 second=tonumber(args[2])
 -- This needs to use if statements as math.random won't accept explicit nil values as arguments.
 iffirstthen
 ifsecondthen
 iffirst>secondthen-- Second number cannot be less than the first, or it causes an error.
 first,second=second,first
 end
 returngetBigRandom(first,second)
 else
 returngetBigRandom(1,first)
 end
 else
 returnmath.random()
 end
 end

 --------------------------------------------------------------------------------------
 -- Date function
 --------------------------------------------------------------------------------------

 functionl.date(args)
 -- This function gets random dates, and takes timestamps as positional arguments.
 -- With no arguments specified, it outputs a random date in the current year.
 -- With two arguments specified, it outputs a random date between the timestamps.
 -- With one argument specified, the date is a random date between the unix epoch (1 Jan 1970) and the timestamp.
 -- The output can be formatted using the "format" argument, which works in the same way as the #time parser function.
 -- The default format is the standard Wikipedia timestamp.
 locallang=mw.language.getContentLanguage()

 localfunctiongetDate(format,ts)
 localsuccess,date=pcall(lang.formatDate,lang,format,ts)
 ifsuccessthen
 returndate
 end
 end

 localfunctiongetUnixTimestamp(ts)
 localunixts=getDate('U',ts)
 ifunixtsthen
 returntonumber(unixts)
 end
 end

 localt1=args[1]
 localt2=args[2]

 -- Find the start timestamp and the end timestamp.
 localstartTimestamp,endTimestamp
 ifnott1then
 -- Find the first and last second in the current year.
 localcurrentYear=tonumber(getDate('Y'))
 localcurrentYearStartUnix=tonumber(getUnixTimestamp('1 Jan '..tostring(currentYear)))
 localcurrentYearEndUnix=tonumber(getUnixTimestamp('1 Jan '..tostring(currentYear+1)))-1
 startTimestamp='@'..tostring(currentYearStartUnix)-- @ is used to denote Unix timestamps with lang:formatDate.
 endTimestamp='@'..tostring(currentYearEndUnix)
 elseift1andnott2then
 startTimestamp='@0'-- the Unix epoch, 1 January 1970
 endTimestamp=t1
 elseift1andt2then
 startTimestamp=t1
 endTimestamp=t2
 end

 -- Get Unix timestamps and return errors for bad input (or for bugs in the underlying PHP library, of which there are unfortunately a few)
 localstartTimestampUnix=getUnixTimestamp(startTimestamp)
 localendTimestampUnix=getUnixTimestamp(endTimestamp)
 ifnotstartTimestampUnixthen
 returnraiseError('"'..tostring(startTimestamp)..'" was not recognised as a valid timestamp')
 elseifnotendTimestampUnixthen
 returnraiseError('"'..tostring(endTimestamp)..'" was not recognised as a valid timestamp')
 elseifstartTimestampUnix>endTimestampUnixthen
 returnraiseError('the start date must not be later than the end date (start date: "'..startTimestamp..'", end date: "'..endTimestamp..'")')
 end

 -- Get a random number between the two Unix timestamps and return it using the specified format.
 localrandomTimestamp=getBigRandom(startTimestampUnix,endTimestampUnix)
 localdateFormat=args.formator'H:i, d F Y (T)'
 localresult=getDate(dateFormat,'@'..tostring(randomTimestamp))
 ifresultthen
 returnresult
 else
 returnraiseError('"'..dateFormat..'" is not a valid date format')
 end
 end

 --------------------------------------------------------------------------------------
 -- List functions
 --------------------------------------------------------------------------------------

 localfunctionrandomizeArray(t,limit)
 -- Randomizes an array. It works by iterating through the list backwards, each time swapping the entry
 -- "i" with a random entry. Courtesy of Xinhuan at http://forums.wowace.com/showthread.php?p=279756
 -- If the limit parameter is set, the array is shortened to that many elements after being randomized.
 -- The lowest possible value is 0, and the highest possible is the length of the array.
 locallen=#t
 fori=len,2,-1do
 localr=math.random(i)
 t[i],t[r]=t[r],t[i]
 end
 iflimitandlimit<lenthen
 localret={}
 fori,vinipairs(t)do
 ifi>limitthen
 break
 end
 ret[i]=v
 end
 returnret
 else
 returnt
 end
 end

 localfunctionremoveBlanks(t)
 -- Removes blank entries from an array so that it can be used with ipairs.
 localret={}
 fork,vinpairs(t)do
 iftype(k)=='number'then
 table.insert(ret,k)
 end
 end
 table.sort(ret)
 fori,vinipairs(ret)do
 ret[i]=t[v]
 end
 returnret
 end

 localfunctionmakeSeparator(sep)
 ifsep=='space'then
 -- Include an easy way to use spaces as separators.
 return' '
 elseifsep=='newline'then
 -- Ditto for newlines
 return'\n'
 elseiftype(sep)=='string'then
 -- If the separator is a recognised MediaWiki separator, use that. Otherwise use the value of sep if it is a string.
 localmwseparators={'dot','pipe','comma','tpt-languages'}
 for_,mwsepinipairs(mwseparators)do
 ifsep==mwsepthen
 returnmw.message.new(sep..'-separator'):plain()
 end
 end
 returnsep
 end
 end

 localfunctionmakeRandomList(args)
 locallist=removeBlanks(args)
 list=randomizeArray(list,tonumber(args.limit))
 returnlist
 end

 functionl.item(args)
 -- Returns a random item from a numbered list.
 locallist=removeBlanks(args)
 locallen=#list
 iflen>=1then
 returnlist[math.random(len)]
 end
 end

 functionl.list(args)
 -- Randomizes a list and concatenates the result with a separator.
 locallist=makeRandomList(args)
 localsep=makeSeparator(args.seporargs.separator)
 returntable.concat(list,sep)
 end

 functionl.text_list(args)
 -- Randomizes a list and concatenates the result, text-style. Accepts separator and conjunction arguments.
 locallist=makeRandomList(args)
 localsep=makeSeparator(args.seporargs.separator)
 localconj=makeSeparator(args.conjorargs.conjunction)
 returnmw.text.listToText(list,sep,conj)
 end

 functionl.array(args)
 -- Returns a Lua array, randomized. For use from other Lua modules.
 returnrandomizeArray(args.t,args.limit)
 end

 --------------------------------------------------------------------------------------
 -- HTML list function
 --------------------------------------------------------------------------------------

 functionl.html_list(args,listType)
 -- Randomizes a list and turns it into an HTML list. Uses [[Module:List]].
 listType=listTypeor'bulleted'
 locallistArgs=makeRandomList(args)-- Arguments for [[Module:List]].
 fork,vinpairs(args)do
 iftype(k)=='string'then
 listArgs[k]=v
 end
 end
 returnmakeList(listType,listArgs)
 end

 --------------------------------------------------------------------------------------
 -- The main function. Called from other Lua modules.
 --------------------------------------------------------------------------------------

 functionp.main(funcName,args,listType)
 -- Sets the seed for the random number generator and passes control over to the other functions.
 localsame=yesno(args.same)
 ifnotsamethen
 -- Generates a different number every time the module is called, even from the same page.
 -- This is because of the variability of os.clock (the time in seconds that the Lua script has been running for).
 math.randomseed(mw.site.stats.edits+mw.site.stats.pages+os.time()+math.floor(os.clock()*1000000000))
 else
 ifnotcfg.lowTrafficthen
 -- Make the seed as random as possible without using anything time-based. This means that the same random number
 -- will be generated for the same input from the same page - necessary behaviour for some wikicode templates that
 -- assume bad pseudo-random-number generation.
 localstats=mw.site.stats
 localviews=stats.viewsor0-- This is not always available, so we need a backup.
 localseed=views+stats.pages+stats.articles+stats.files+stats.edits+stats.users+stats.activeUsers+stats.admins-- Make this as random as possible without using os.time() or os.clock()
 math.randomseed(seed)
 else
 -- Make the random seed change every n seconds, where n is set by cfg.seedRefreshRate.
 -- This is useful for low-traffic wikis where new edits may not happen very often.
 math.randomseed(math.floor(os.time()/cfg.seedRefreshRate))
 end
 end
 iftype(args)~='table'then
 error('the second argument to p.main must be a table')
 end
 returnl[funcName](args,listType)
 end

 --------------------------------------------------------------------------------------
 -- Process arguments from #invoke
 --------------------------------------------------------------------------------------

 localfunctionmakeWrapper(funcName,listType)
 -- This function provides a wrapper for argument-processing from #invoke.
 -- listType is only used with p.html_list, and is nil the rest of the time.
 returnfunction(frame)
 -- If called via #invoke, use the args passed into the invoking template, or the args passed to #invoke if any exist.
 -- Otherwise assume args are being passed directly in from the debug console or from another Lua module.
 localorigArgs
 ifframe==mw.getCurrentFrame()then
 origArgs=frame:getParent().args
 fork,vinpairs(frame.args)do
 origArgs=frame.args
 break
 end
 else
 origArgs=frame
 end
 -- Trim whitespace and remove blank arguments.
 localargs={}
 fork,vinpairs(origArgs)do
 iftype(v)=='string'then
 v=mw.text.trim(v)
 end
 ifv~=''then
 args[k]=v
 end
 end
 returnp.main(funcName,args,listType)
 end
 end

 -- Process arguments for HTML list functions.
 localhtmlListFuncs={
 bulleted_list='bulleted',
 unbulleted_list='unbulleted',
 horizontal_list='horizontal',
 ordered_list='ordered',
 horizontal_ordered_list='horizontal_ordered'
 }
 forfuncName,listTypeinpairs(htmlListFuncs)do
 p[funcName]=makeWrapper('html_list',listType)
 end

 -- Process arguments for other functions.
 localotherFuncs={'number','date','item','list','text_list'}
 for_,funcNameinipairs(otherFuncs)do
 p[funcName]=makeWrapper(funcName)
 end

 returnp

AltStyle によって変換されたページ (->オリジナル) /