lua做成exe

Lua是一门脚本语言,通常以解释执行的方式运行,但若希望把Lua脚本转换成独立的exe文件,可以使用诸如luac等工具对Lua源码进行编译,生成字节码,然后配合C语言的宿主程序进行打包。下面是一份简易的Lua打包成exe的教程:

需要的工具和程序库:

1. Lua:Lua官方提供宿主程序接口和库文件

官网地址:https://www.lua.org/

下载对应的版本,本教程以Lua5.3为例。

2. MinGW:C编译环境,用于编译链接Lua和C程序

官网地址:http://mingw-w64.org/

安装时选择“MinGW-w64”和“x86_64”架构,默认安装位置为C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0。

3. luac:Lua编译器,将Lua代码编译为字节码,用于后续C程序引用。

在官网下载的Lua源码包中包含本工具。位于src文件夹中。

步骤:

1. 安装MinGW,并将C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin添加到系统环境变量Path中。

2. 编译安装Lua库

进入Lua源码的src目录,运行如下命令:

```

mingw32-make PLAT=mingw

```

编译成功后,将src目录下的liblua.a拷贝至C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\lib,并把src中的lua.h、luaconf.h、lauxlib.h、lualib.h拷贝至C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\include文件夹。

3. 编写Lua脚本

编写一个简单的Lua脚本hello.lua,内容如下:

```

print("Hello, World!")

```

使用luac编译成hello.out字节码文件:

```

luac -o hello.out hello.lua

```

4. 编写C程序,用于嵌入Lua脚本

编写C程序文件launcher.c,内容如下:

```c

#include

#include

#include

#include

/* 字节码数组,正式环境需要使用字节码转换工具将字节码转为数组,替换下面的greetings */

static const unsigned char hello_out[] = { /*hello.out字节码数组*/ };

int main(void) {

lua_State *L = luaL_newstate();

luaL_openlibs(L);

luaL_loadbuffer(L, (const char*)hello_out, sizeof(hello_out), "hello.out");

lua_pcall(L, 0, 0, 0);

lua_close(L);

return 0;

}

```

5. 编译链接C程序和Lua字节码

使用gcc编译并链接C程序和Lua库:

```

gcc -o launcher.exe launcher.c -llua -L"C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\lib"

```

6. 运行exe文件

双击运行生成的launcher.exe,将看到"Hello, World!"输出。

以上就是使用Lua和C语言嵌入方式来将Lua脚本打包成exe的基本步骤。需要注意,这里的字节码数组需要手动转换,具体方法是读取字节码文件到数组然后替换代码中静态字节数组。