如何使用lua

时间:2018-02-15 22:58:27

标签: serialization lua schema deserialization lua-table

我有下表:

local obj = {
    firstname = "John",
    lastname  = "Bush",
    age = 22,
    height = 186,
    friends = {
        { firstname = "Paul", lastname = "Graham", age = 20, height = 178 },
        { firstname = "Gianou", lastname = "Kwnstantina", age = 25, height = 172 }
    },
    bodies = { 4, 3, 10 }
}

我希望将其转换为:(插入数据库时​​)

local tuple = {
    'John', 'Bush', 22, 186, { { 'Paul', 'Graham', 20, 178 }, { 'Gianou', 'Kwnstantina', 25, 172 } }, { 4, 3, 10 }
}

我设法使用:

生成
function encode(schema, data)
    local array = {}

    function rec(arr, schema, d)

        for i, field in ipairs(schema) do

            arr[i] = {}
            if field.type == "array" and type(field.items) == "table" then

                for it, piece in ipairs(d[field.name]) do
                    arr[i][it] = {}
                    rec(arr[i][it], field.items, piece)
                end

            else

                arr[i] = d[field.name]

            end

        end
    end

    rec(array, schema, data)

    return array
end

我的问题是,当我检索它时,我想将数据重建为初始形式。我找到了一些可以在其他语言中执行此操作的工具,但问题是他们将数据转换为二进制,我只想要那个数组。

为了能够重建,我需要像模式这样的东西:

local schema = {
    { name = "firstname", type = "string" },
    { name = "lastname", type = "string" },
    { name = "age", type = "int" },
    { name = "height", type = "int" },
    { name = "friends", type = "array", items = {
        { name = "firstname", type = "string" },
        { name = "lastname", type = "string" },
        { name = "age", type = "int" },
        { name = "height", type = "int" }
    }},
    { name = "bodies", type = "array", items = "int"}    
}

我发现仅仅通过检索值来编码它很容易,但是能够验证和解码它似乎很难,是否有计算机科学或库中的此操作的概念(名称)我可以学习(它需要使用架构)? 我需要一个谷歌的关键字...

谢谢!

编辑:只需反转编码我找到了一种简单的解码方法。

function decode(schema, data)
    local obj = {}

    function rec(object, sch, d)
        for i, field in ipairs(sch) do

            if field.type == "array" and type(field.items) == "table" then
                object[field.name] = {}

                for it, piece in ipairs(d[i]) do

                    object[field.name][it] = {}

                    rec(object[field.name][it], field.items, piece)
                end

            else
                object[field.name] = d[i]
            end


        end
    end

    rec(obj, schema, data)

    return obj
end

我仍然喜欢有关代码的建议,我在哪里可以找到有关此类信息的更多信息。

目前的版本:https://pastebin.com/Ub4vZ0GU

0 个答案:

没有答案