Creating standalone Lua executables

后端 未结 6 1364
天命终不由人
天命终不由人 2020-12-02 08:37

Is there an easy way to create standalone .exe files from Lua scripts? Basically this would involve linking the Lua interpreter and the scripts.

I believe it is poss

6条回答
  •  无人及你
    2020-12-02 09:16

    To make executable from script use bin2c utility such way:

    luac script.lua -o script.luac
    bin2c script.luac > code.c
    

    Then create in text editor file main.c and compile/link it with your favorite compiler. That's it. (Note - executable also supports command line args)

    Example with MSVC:

    cl /I "./" /I "$(LUA_DIR)\include" /D "_CRT_SECURE_NO_DEPRECATE" /D "_MBCS" /GF /FD /EHsc /MD /Gy /TC /c main.c
    ld /SUBSYSTEM:CONSOLE /RELEASE /ENTRY:"mainCRTStartup" /MACHINE:X86 /MANIFEST $(LUA_DIR)\lib\lua5.1.lib main.obj /out:script.exe
    mt -manifest $script.manifest -outputresource:script.exe;1
    

    Use /SUBSYSTEM:WINDOWS for GUI executable. All that isn't easy just for the 1st time, you can create batch file to automate the process once you successfuly try it.

    main.c:

    #include 
    #include 
    #include "lua.h"
    #include "lauxlib.h"
    #include "lualib.h"
    
    int main(int argc, char *argv[]) {
      int i;
      lua_State *L = luaL_newstate();
      luaL_openlibs(L);
      lua_newtable(L);
      for (i = 0; i < argc; i++) {
        lua_pushnumber(L, i);
        lua_pushstring(L, argv[i]);
        lua_rawset(L, -3);
      }
      lua_setglobal(L, "arg");
    #include "code.c"
      lua_close(L);
      return 0;
    }
    

提交回复
热议问题