确定 Lua 编译器是运行 32 位还是 64 位

Determine whether Lua compiler runs 32 or 64 bit

我目前在我的默认开发系统上使用 Windows,在我部署 Lua 脚本的服务器上使用 Linux。对于 Windows,只有几个 32 位解释器,例如我目前使用的 Lua for Windows(至少据我所知)。在服务器上,解释器是 运行 64 位脚本。

现在我的问题是:是否可以检查脚本是 运行 的架构(可能类似于版本的 _ENV 变量)?

If there is any 64 bit Windows Lua interpreter feel free to leave a comment on this matter. Thank you in advance.

你为什么需要这些知识?

通常,在 Lua 端,您无能为力,这取决于底层主机体系结构。要执行特定于主机的某些操作,您需要编写一些本机代码,但随后您将了解要针对其编译的体系结构。

虽然有一种可能的方法(也许还有更多)。您可以使用 string.dump() 编译虚拟函数并分析字节码 header。 header 与 Lua 版本不同,因此您应该先检查版本以了解 "system parameters" 字段的位置。如果未更改 Lua 解释器,则存储 size_t 大小(以字节为单位)的字段对于 32 位和 64 位主机将有所不同。

这是确定您的 OS 位数的方法,而不是您的编译器位数(您可以 运行 32 位 Lua.exe 在 Windows 64 位上)。

local arch
if (os.getenv"os" or ""):match"^Windows" then
   print"Your system is Windows"
   arch = os.getenv"PROCESSOR_ARCHITECTURE"
else
   print"Your system is Linux"
   arch = io.popen"uname -m":read"*a"
end
if (arch or ""):match"64" then
   print"Your system is 64-bit"
else
   print"Your system is 32-bit"
end

如果你能拿到executable that runs the script, you can probably look at its header on Windows and Linux to check if it's 32bit or 64bit application; here are suggestions on how to do it on Windows.

我也对使用 Lua 脚本(以及与 Lua 和 LuaJIT 解释器一起使用的脚本)的更简单方法感兴趣,因为我 运行 当我想根据是否需要加载 32 位或 64 位库来引用不同的路径时,用户不必指定这些路径。

最简单的方法就是测试人数限制。在 32 位 Lua 中,0xffffffff(8'f's) 将是最大 int 数,而 0xfffffffff(9'f's) 将溢出 尝试流畅的代码

function _86or64()
    if(0xfffffffff==0xffffffff) then return 32 else return 64 end
end

print(_86or64());

这里有一个函数可以告诉您是在 32 位还是 64 位 LUA:

function bits() return 1<<32==0 and 32 or 1<<64==0 and 64 end