利用 premake5 生成 lua 脚本字节数组嵌入到 C 代码里

premake5 主要由 lua 写成,修改了 lua 加载脚本的方式,将工程用到的 lua 脚本统统转换为 C 代码的字节数组并加载之。

对于一些变动不大的通用的库的来说,改为字节数组加载更方便。

premake5 提供了一个 premake-core/scripts/embed.lua 用于生成脚本到字节数组,我们修改之为己所用。

修改过的 embed.lua

--
-- Embed the Lua scripts into src/host/scripts.c as static data buffers.
-- Embeds minified versions of the actual scripts by default, rather than
-- bytecode, as bytecodes are not portable to different architectures. Use
-- the `--bytecode` flag to override.
--    

    local scriptCount = 0

    local function loadScript(fname)
        fname = path.getabsolute(fname)
        local f = io.open(fname, "rb")
        local s = assert(f:read("*all"))
        f:close()
        return s
    end


    local function stripScript(s)
        -- strip tabs
        local result = s:gsub("[\t]", "")

        -- strip any CRs
        result = result:gsub("[\r]", "")

        -- strip out block comments
        result = result:gsub("[^\"']%-%-%[%[.-%]%]", "")
        result = result:gsub("[^\"']%-%-%[=%[.-%]=%]", "")
        sresult = result:gsub("[^\"']%-%-%[==%[.-%]==%]", "")

        -- strip out inline comments
        result = result:gsub("\n%-%-[^\n]*", "\n")

        -- strip duplicate line feeds
        result = result:gsub("\n+", "\n")

        -- strip out leading comments
        result = result:gsub("^%-%-[^\n]*\n", "")

        return result
    end


    local function outputScript(result, script)
        local data   = script.data
        local length = #data

        if length > 0 then
            script.table = string.format("builtin_script_%d", scriptCount)
            scriptCount = scriptCount + 1

            buffered.writeln(result, "// ".. script.name)
            buffered.writeln(result, "static const unsigned char " .. script.table .. "[] = {")

            for i = 1, length do
                buffered.write(result, string.format("%3d, ", data:byte(i)))
                if (i % 32 == 0) then
                    buffered.writeln(result)
                end
            end

            buffered.writeln(result, "};")
            buffered.writeln(result)
        end
    end


    local function addScript(result, filename, name, data)
        if not data then
            if _OPTIONS["bytecode"] then
                verbosef("Compiling... " .. filename)
                local output = path.replaceextension(filename, ".luac")
                local res, err = os.compile(filename, output);
                if res ~= nil then
                    data = loadScript(output)
                    os.remove(output)
                else
                    print(err)
                    print("Embedding source instead.")
                    data = stripScript(loadScript(filename))
                end
            else
                data = stripScript(loadScript(filename))
            end
        end

        local script = {}
        script.filename = filename
        script.name     = name
        script.data     = data
        table.insert(result, script)
    end


-- Prepare the file header

    local result = buffered.new()
    buffered.writeln(result, "/* Premake's Lua scripts, as static data buffers for release mode builds */")
    buffered.writeln(result, "/* DO NOT EDIT - this file is autogenerated - see BUILD.txt */")
    buffered.writeln(result, "/* To regenerate this file, run: premake5 embed */")
    buffered.writeln(result, "")
    buffered.writeln(result, '#include "host/premake.h"')
    buffered.writeln(result, "")

-- Find all of the _manifest.lua files within the project

    local mask = path.join(_MAIN_SCRIPT_DIR, "**/_manifest.lua")
    local manifests = os.matchfiles(mask)


-- Generate table of embedded content.
    local contentTable = {}

    print("Compiling... ")
    for mi = 1, #manifests do
        local manifestName = manifests[mi]
        local manifestDir  = path.getdirectory(manifestName)
        local baseDir      = path.getdirectory(manifestDir)      

        local files = dofile(manifests[mi])
        for fi = 1, #files do
            local filename = path.join(manifestDir, files[fi])            
            addScript(contentTable, filename, path.getrelative(baseDir, filename))
        end
    end

    --addScript(contentTable, path.join(_SCRIPT_DIR, "../src/_premake_main.lua"), "src/_premake_main.lua")
    addScript(contentTable, path.join(_SCRIPT_DIR, "./lua/_manifest.lua"), "lua/_manifest.lua")



-- Embed the actual script contents

    print("Embedding...")
    for mi = 1, #contentTable do
        outputScript(result, contentTable[mi])
    end

-- Generate an index of the script file names. Script names are stored
-- relative to the directory containing the manifest, i.e. the main
-- Xcode script, which is at $/modules/xcode/xcode.lua is stored as
-- "xcode/xcode.lua".
    buffered.writeln(result, "const buildin_mapping builtin_scripts[] = {")

    for mi = 1, #contentTable do
        if contentTable[mi].table then
            buffered.writeln(result, string.format('\t{"%s", %s, sizeof(%s)},', contentTable[mi].name, contentTable[mi].table, contentTable[mi].table))
        else
            buffered.writeln(result, string.format('\t{"%s", NULL, 0},', contentTable[mi].name))
        end
    end

    buffered.writeln(result, "\t{NULL, NULL, 0}")
    buffered.writeln(result, "};")
    buffered.writeln(result, "")

-- Write it all out. Check against the current contents of scripts.c first,
-- and only overwrite it if there are actual changes.

    print("Writing...")
    local scriptsFile = path.getabsolute(path.join(_SCRIPT_DIR, "./scripts.c"))
    local output = buffered.tostring(result)

    local f, err = os.writefile_ifnotequal(output, scriptsFile);
    if (f < 0) then
        error(err, 0)
    elseif (f > 0) then
        printf("Generated %s...", path.getrelative(os.getcwd(), scriptsFile))
    end

我们的脚本目录结构

lua\util001.lua
lua\_manifest.lua
embed.lua

在 _manifest.lua 中修改需要生成的脚本文件名

return
    {              
        "util001.lua"       
    }

运行以下命令会在 embed.lua 所在目录生成 scripts.c

premake5 --file=embed.lua

生成的 scripts.c

/* Premake's Lua scripts, as static data buffers for release mode builds */
/* DO NOT EDIT - this file is autogenerated - see BUILD.txt */
/* To regenerate this file, run: premake5 embed */

#include "host/premake.h"

// lua/util001.lua
static const unsigned char builtin_script_0[] = {
108, 111,  99,  97, 108,  32, 117, 116, 105, 108,  32,  61,  32, 123, 125,  10,  32,  10, 102, 117, 110,  99, 116, 105, 111, 110,  32, 117, 116, 105, 108,  46, 
116, 101, 115, 116,  40,  97, 114, 103,  41,  10,  32,  32,  32,  32, 112, 114, 105, 110, 116,  40,  97, 114, 103,  41,  10, 101, 110, 100,  10,  32,  10, 114, 
101, 116, 117, 114, 110,  32, 117, 116, 105, 108, };

// lua/_manifest.lua
static const unsigned char builtin_script_1[] = {
114, 101, 116, 117, 114, 110,  10, 123,  10,  32,  32,  32,  32,  32,  32,  32,  32,  45,  45,  32,  99, 106, 115, 111, 110,  10,  32,  32,  32,  32,  32,  32, 
 32,  32,  45,  45,  34,  99, 106, 115, 111, 110,  47, 117, 116, 105, 108,  46, 108, 117,  97,  34,  44,  10,  32,  32,  32,  32,  32,  32,  32,  32,  45,  45, 
 34,  66, 105, 110,  68, 101,  99,  72, 101, 120,  46, 108, 117,  97,  34,  44,  10,  32,  32,  32,  32,  32,  32,  32,  32,  34, 117, 116, 105, 108,  48,  48, 
 49,  46, 108, 117,  97,  34,  10, 125,  10, };

const buildin_mapping builtin_scripts[] = {
    {"lua/util001.lua", builtin_script_0, sizeof(builtin_script_0)},
    {"lua/_manifest.lua", builtin_script_1, sizeof(builtin_script_1)},
    {NULL, NULL, 0}
};

下一节修改自己的 lua 引擎加载代码。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,539评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,594评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,871评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,963评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,984评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,763评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,468评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,850评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,002评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,144评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,823评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,483评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,026评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,150评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,415评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,092评论 2 355

推荐阅读更多精彩内容