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.[1] This lesson will show you how to use the Lua OS library in your scripts.

Prerequisites edit

This lesson assumes you have already completed the Tables lesson.

Create a Lua Script that Uses the OS Library edit

To create a Lua script that uses the OS 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.
  3. Add the following code and save the page:
local p = {}
 
function p.osclock()
    return ';clock\n:' .. os.clock() .. '\n'
end
 
function p.osdate()
    return ';date\n:' .. os.date() .. '\n'
end
 
function p.osdifftime()
    local t1 = {year = 2014, month = 1, day = 1, hour = 0, min = 0, sec = 0, isdst = false}
    local t2 = {year = 2014, month = 12, day = 31, hour = 23, min = 59, sec = 59, isdst = false}
    return ';difftime\n:' .. os.difftime(os.time(t2), os.time(t1)) .. '\n'
end
 
function p.ostime()
    return ';time\n:' .. os.time() .. '\n'
end	
 
return p

Test Your Lua Script edit

To test your Lua script:

  1. Navigate to either the Module_talk:Sandbox page, the Wikiversity:Sandbox page, or your own user or sandbox page.
  2. Add the following code and save the page:
{{#invoke:Sandbox|osclock}}
{{#invoke:Sandbox|osdate}}
{{#invoke:Sandbox|osdifftime}}
{{#invoke:Sandbox|ostime}}

The result should be similar to:

clock
0.003786627
date
Sat 28 Dec 2013 03:20:55 AM UTC
difftime
31535999
time
1388200855

Understand Your Lua Script edit

To understand your Lua script:

  1. os.clock() returns the approximate amount of CPU time used by the script.
  2. os.date() returns the current date.
  3. local t1 = {year = 2014, month = 1, day = 1, hour = 0, min = 0, sec = 0, isdst = false} defines a local variable t1 as a table with the given date and time values.
    isdst = false indicates that the time value is not daylight savings time.
  4. local t2 = {year = 2014, month = 12, day = 31, hour = 23, min = 59, sec = 59, isdst = false} defines a local variable t2 as a table with the given date and time values.
  5. os.difftime(os.time(t2), os.time(t1)) returns the difference in seconds between t1 and t2.
  6. os.time() returns the current time in seconds.

Conclusion edit

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

See Also edit

References edit