io.popen() function in Lua Programming

LuaServer Side ProgrammingProgramming

Sometimes we want to execute the system's command and then make use of whatever was returned by them, and in order to do that we simply can either make use of the os.execute() function or io.popen() function.

The difference between the os.execute() function and the io.popen() function is that the output value of the os.execute() function is much harder to deal with, and that is the reason why it is recommended to use the io.popen() function, whose output value is much easier to handle and make use of.

io.popen() starts the program in a separate process and returns a file handle that you can use to read data from this program.

Syntax

output = io.popen(command)

Now that we know what io.popen() function does, let’s use it in a Lua example.

Example

Consider the example shown below −

local handle = io.popen("echo hello")
local result = handle:read("*a")
handle:close()

In the above code, we made use of io.popen that returns a file handle that we can use to read the output of the command.

Output

hello
raja
Published on 20-Jul-2021 13:43:17
Advertisements