Using the os Libary

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.



Screen Shot 2021-03-30 at 8.45.32 AM

You can pass in any command that the OS's terminal can execute.

Screen Shot 2021-03-30 at 8.47.21 AM


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.


Screen Shot 2021-03-30 at 8.50.27 AM

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".

Screen Shot 2021-03-30 at 8.54.51 AM



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.


Screen Shot 2021-03-30 at 9.04.04 AM

os.clock() returns the number of seconds since Lua was started (not the OS.)

You can use c-style strftime parameters with os.date.

Screen Shot 2021-03-30 at 9.05.53 AM


Those are the main os library functions.

This site does not track your information.