Lua/OS Library
< Lua
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
editThis lesson assumes you have already completed the Tables lesson.
Create a Lua Script that Uses the OS Library
editTo create a Lua script that uses the OS library:
- Navigate to Module:Sandbox.
- 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.
- 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
editTo test your Lua script:
- Navigate to either the Module_talk:Sandbox page, the Wikiversity:Sandbox page, or your own user or sandbox page.
- 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
editTo understand your Lua script:
os.clock()
returns the approximate amount of CPU time used by the script.os.date()
returns the current date.local t1 = {year = 2014, month = 1, day = 1, hour = 0, min = 0, sec = 0, isdst = false}
defines a local variablet1
as a table with the given date and time values.isdst = false
indicates that the time value is not daylight savings time.
local t2 = {year = 2014, month = 12, day = 31, hour = 23, min = 59, sec = 59, isdst = false}
defines a local variablet2
as a table with the given date and time values.os.difftime(os.time(t2), os.time(t1))
returns the difference in seconds betweent1
andt2
.os.time()
returns the current time in seconds.
Conclusion
editCongratulations! 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.