Lua/Table Library

Lua modules based on the Scribunto/Lua extension are stored in resource pages using the Module: namespace. Each module uses a table to hold functions and variables, and that containing table is returned at the end of the module code. This lesson will show you how to use the Lua Table library in your scripts.

Prerequisites
This lesson assumes you have already completed the Tables lesson.

Create a Lua Script that Uses the Table Library
To create a Lua script that uses the Table library: ""
 * 1) Navigate to Module:Sandbox.
 * 2) Clear all existing code.
 * It's a sandbox. Everyone is free to play in the sandbox.  But if you find another user is actively editing the sandbox at the same time, you may also use Module:Sandbox/Username, where Username is your Wikiversity username.
 * 1) Add the following code and save the page:

Test Your Lua Script
To test your Lua script:
 * 1) Navigate to either the Module_talk:Sandbox page, the Sandbox page, or your own user or sandbox page.
 * 2) Add the following code and save the page:

The result should be similar to:
 * random numbers
 * 2, 7, 5, 7, 5, 4, 9, 1, 10, 4


 * sorted numbers
 * 1, 2, 4, 4, 5, 5, 7, 7, 9, 10


 * after removing the first value
 * 2, 4, 4, 5, 5, 7, 7, 9, 10


 * sorted in descending order
 * 10, 9, 7, 7, 5, 5, 4, 4, 2

Understand Your Lua Script
To understand your Lua script  function:
 * 1)   declares a local function named   that accepts two parameters,   and.
 * 2)   returns true if the first is greater than the second, which will result in values being sorted in descending order.

To understand your Lua script  function:
 * 1)   defines an empty table variable named.
 * 2)   seeds the Lua random number generator with the current server operating system elapsed time in seconds.
 * 3) * If the random number generator is not seeded, it will return the same sequence of numbers every time.
 * 4) * The MediaWiki software caches page results. It is necessary to purge the server page cache to see new results.  See  for more information.
 * 5)   creates a loop code block that will repeat   times.
 * 6)   calls the   library   function to retrieve a random number between   and , inclusive, and then inserts that value into the   table.
 * 7)   retrieves the values in the table   and converts them into a string concatenated with   separators between each value.
 * 8)   sorts the   table in the default ascending order.
 * 9)   removes the element in position   from the table.
 * Since the table was sorted prior to removal, this will remove the lowest value from the table.
 * 1)   sorts the table using a custom   comparison function.

Conclusion
Congratulations! You've now created, tested, and understood a Lua script that uses the Table library. Return to the main Lua page to learn about other Lua code libraries.