如何使用另一个词典的内容替换缺失的内容?

所以,我正在为一个游戏进行翻译,并且我有不同的词典。如果一个翻译在某个语言中不存在,我想将其设置为英语翻译。但我尝试过的每种组合词典的方法都非常低效。

这里是一些简化的例子

local translation-sr = {
    Buttons = {
        Confirm = "Потврди";
        Submit = "Унеси";
    };
    Countries = {
        Bloxell = "Блоксел";
        USA = "Сједињене Америчке Државе";
    };
    Firearms = {
        Manufacturers = {
            GenMot = "Џенерални Мотори";
            Intratec = "Интратек";
            TF = "ТФ Оружје";
        };
    };
};

local translation-en = {
    Buttons = {
        Confirm = "Confirm";
        Purchase = "Purchase";
        Submit = "Submit";
    };
    Countries = {
        Bloxell = "Bloxell";
        USA = "United States";
    };
    Firearms = {
        Manufacturers = {
            GenMot = "General Motors";
            Intratec = "Intratec";
            TF = "TF Armaments";
        };
    };
    Languages = {
        Belarusian = "Belarusian";
        English = "English";
        French = "French";
        German = "German";
        Italian = "Italian";
        Russian = "Russian";
        Serbian = "Serbian";
        Spanish = "Spanish";
    };
};
点赞
用户107090
用户107090

我猜你想要像这样做:

setmetatable(translation_sr.Buttons,{__index=translation_en.Buttons})

针对所有叶子子表。如果只有几个子表,你可以手动完成这个任务。

2019-01-03 16:22:00
用户7396148
用户7396148

我认为你应该使用一个元表来完成你需要的功能。

我假设你总是通过英语默认单词进行索引。 如果是这样,你可以做如下操作。

local function default(t,k)
    return k
end

local translation_sr = {
    Button = setmetatable({
        Confirm = "Потврди",
        Submit = "Унеси",
    },
    { __index = default }),

    Countries = setmetatable({
        ["Bloxell"] = "Блоксел",
        ["United States"]= "Сједињене Америчке Државе",
    },
    { __index = default }),

    Firearms = {
        Manufacturers = setmetatable({
            ["General Motors"] = "Џенерални Мотори",
            ["Intratec"] = "Интратек",
            ["TF Armaments"] = "ТФ Оружје",
        },
        { __index = default }),
    },
}

这个函数只是返回在表中不存在的键。

local function default(t,k)
    return k
end

在假设英语单词作为默认值的情况下,你可以从 translation_sr 获取 "Purchase" 的返回值为 "Purchase"。 这种方法不需要 translation_en 表。

2019-01-03 16:23:43