Using the os Libary
03/30/21 08:17 Filed in: Lua
Today, I learn a few miscellaneous things about Lua. I don't want to tackle any big topics, because my day is full.
Executing Other Programs
I often write code to run other programs, programs I didn't write or want to write. Even though, Lua is an embeddable language that runs on different platforms, it has a library, os, that standardizes calls to the underlying OS. Even if I never embed Lua, I still can use the os library.
You can communicate with the underlying OS by way of the os.execute function. You can also use it to determine if the OS has a shell you can communicate with.
local code = os.execute()
This returns a code:
- 0 if there is no shell, or Lua is embedded.
- Non-0 a shell exists
- Nothing, a shell exists
If you pass a string command into os.execute, Lua will try to execute it by passing it to the shell. Let's try something simple.
You can pass in any command that the OS's terminal can execute.
In addition to os.execute, there is another useful command:
os.getenv("PATH")
which returns the contents of the PATH on systems that support one.
More About Files
I already went over how to open, read, write, and close files using the io library. There are functions that are specific to the OS, things such as creating directories. You can use execute to do just that. Here is an example of me playing around with the command to create a folder I've cleverly called "FOLDER".
Executing mkdir FOLDER returns three values.
First true if the command executed normally, nil if not.
Second, exit or signal indicating if the command exited normally or with an error (signal).
Third, the actual signal number.
You can see examples of this above when I try to create the same folder again.
Additionally, os has the following functions:
- os.rename()
- os.remove()
- os.tmpname() which generates a temporary file name.
System Clock
Other useful os functions are clock and date.
os.clock() returns the number of seconds since Lua was started (not the OS.)
You can use c-style strftime parameters with os.date.
Those are the main os library functions.