5

I mean the situation when lua is run not as embedded in another app but as standalone scripting language.

I need something like PHP_BINARY or sys.executable in python. Is that possible with LUA ?

rsk82
  • 28,217
  • 50
  • 150
  • 240

3 Answers3

4

Try arg[-1]. But note that arg is not defined when Lua is executed interactively.

lhf
  • 70,581
  • 9
  • 108
  • 149
4

Note that the the solution given by lhf is not the most general. If the interpreter has been called with additional command line parameters (if this may be your case) you will have to search arg.

In general the interpreter name is stored at the most negative integer index defined for arg. See this test script:

local i_min = 0
while arg[ i_min ] do i_min = i_min - 1 end
i_min = i_min + 1   -- so that i_min is the lowest int index for which arg is not nil

for i = i_min, #arg do
    print( string.format( "arg[%d] = %s", i, arg[ i ] ) )
end
0

If the directory that contains your Lua interpreter is in your PATH environment variable, and you invoked the Lua interpreter by its file name:

lua myprog.lua

then arg[-1] contains "lua", not the absolute path of the Lua interpreter.

The following Lua program works for me on z/OS UNIX:

-- Print the path of the Lua interpreter running this program

posix = require("posix")
stringx = require("pl.stringx")

-- Returns output from system command, trimmed
function system(cmd)
  local f = assert(io.popen(cmd, "r"))
  local s = assert(f:read("*a"))
  f:close()
  return stringx.strip(s)
end

-- Get process ID of current process
-- (the Lua interpreter running this Lua program)
local pid = posix.getpid("pid")

-- Get the "command" (path) of the executable program for this process
local path = system("ps -o comm= -p " .. pid)

-- Is the path a symlink?
local symlink = posix.readlink(path)

if symlink then
  print("Path (a symlink): " .. path)
  print("Symlink refers to: " .. symlink)
else
  print("Path (actual file, not a symlink): " .. path)
end

Alternatively, on UNIX operating systems that have a proc filesystem, you can use readlink("/proc/self/exe") to get the path.

Graham Hannington
  • 1,749
  • 16
  • 18