Linux Format

Doing systems programmin­g in Lua

-

Although Lua is not a systems programmin­g language, it can interact with the operating system using the Operating System library. However, the Operating System library only provides two functions for file manipulati­on: os.rename and os.remove which are for renaming and deleting a file respective­ly. The following Lua code shows you how to read environmen­t variables: > print(os.getenv("PATH")) /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin > print(os.getenv("DOESNOTEXI­ST")) nil

As you can see, if the variable you are trying to read isn’t defined, the call returns nil.

The os.clock() function returns an approximat­ion of the amount of CPU time in seconds. You call it as follows: > print(os.clock()) 0.003559

The os.difftime(t2, t1) function returns the difference in seconds between two times whereas the os.date() returns the date as a string using the MM/DD/YY HH:MM:SS format. The os.execute([command]) function allows you to run external commands and is analogous to the system(3) C system call. The os.exit([code]) command uses the exit(3) C function to terminate the host program with an optional exit code. Last, the os.tmpname() function creates a

temporary file without opening it which is a job for the developer. The following Lua code demonstrat­es how to extract the various components of the os.date() command: > t = os.date('*t') > for key, value in pairs(t) do print(key,value) end

The first command produces a table that is being processed and printed using the pairs() command which allows iteration over key and value pairs. Please note that the table.foreach() is deprecated and should be replaced by the

pairs() function. As you can probably appreciate from what we’ve covered here, performing systems programmin­g in Lua is a challenge.

Newspapers in English

Newspapers from Australia