Is there a way to get the path and name of the interpreter that works with the current script?

I mean the situation when lua is launched not as a built-in other application, but as a stand-alone scripting language.

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

+4
source share
3 answers

Note that the solution given by lhf is not the most general. If the interpreter was invoked with additional command line parameters (if this may be your case), you will have to look for arg .

In the general case, the name of the interpreter is stored in 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 
+4
source

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

+4
source

If the directory containing your Lua interpreter is in your PATH environment variable, and you called the Lua interpreter by 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 with the proc file system, you can use readlink("/proc/self/exe") to get the path.

0
source

Source: https://habr.com/ru/post/1497397/


All Articles