23

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

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
henryaz
  • 870
  • 1
  • 8
  • 18

3 Answers3

34

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)
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
3

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

jbochi
  • 28,816
  • 16
  • 73
  • 90
Tom Regner
  • 6,856
  • 4
  • 32
  • 47
3

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.

  • The third digit identifies different bug-fix releases with no change of functionality. It seems pointless to test those. – lhf Aug 19 '13 at 00:32
  • @lhf in general I fully agree, but for special needs it is a trick useful to know. E.g. say you want to discover if your script is run by an interpreter that has a particular patch applied or it is an older one (maybe you must run the script on a system not under your control, so you don't know whether a workaround in the code must be used or not). But I admit it is a bit on the nitpicker's side :-) – LorenzoDonati4Ukraine-OnStrike Aug 19 '13 at 00:43
  • On Linux '`lua -v`' writes to `stdout` with Lua 5.2 but to `stderr` with Lua 5.1, but since the syntax for the redirection is the same in the (Bourne) shell, you can use the same command string on Linux and Windows (and almost certainly on OS X too). – Chris Arndt Sep 27 '14 at 14:33