In Lua, is there a function that will tell me what

2019-02-05 22:44发布

问题:

Subject says it all. I would like to know if my host interpreter is running Lua 5.2 or 5.1

回答1:

There is global variable _VERSION (a string):

print(_VERSION)

-- Output
Lua 5.2

UPD :
Other methods to distinguish between Lua versions:

if _ENV then 
  -- Lua 5.2
else
  -- Lua 5.1
end

UPD2 :

--[=[
local version = 'Lua 5.0'
--[[]=]
local n = '8'; repeat n = n*n until n == n*n
local t = {'Lua 5.1', nil,
  [-1/0] = 'Lua 5.2',
  [1/0]  = 'Lua 5.3',
  [2]    = 'LuaJIT'}
local version = t[2] or t[#'\z'] or t[n/'-0'] or 'Lua 5.4'
--]]
print(version)


回答2:

If you also need the third digit in Lua version (not available in _VERSION) you need to parse the output of lua -v command on the command line.

For platforms that support io.popen this script will do the trick, but only if the script is run by the standalone interpreter (not in interactive mode).IOW the arg global table must be defined:

local i_min = 0
while arg[ i_min ] do i_min = i_min - 1 end
local lua_exe = arg[ i_min + 1 ]

local command = lua_exe .. [[ -v 2>&1]] -- Windows-specific
local fh = assert( io.popen( command ) )
local version = fh:read '*a'
fh:close()

-- use version in the code below

print( version )
print( version:match '(%d%.%d%.%d)' )

Note that lua -v writes on stderr on Windows (for Linux I don't know), so the command for io.popen (which only captures stdout) must redirect stderr to stdout and the syntax is platform-specific.



回答3:

_VERSION holds the interpreter version. Check the manual for reference.



标签: lua version