更新表中的元素而不更改表顺序Lua

时间:2017-10-22 12:22:39

标签: lua

我想在Lua中更新表值时维护表的顺序。

实施例

tbl = {
        messageId = 0,
        timestamp = currentTime,
        responseStatus = {
            status = "FAILED",
            errorCode = "599",
            errorMessage = "problem"
        }
    }

意味着tbl.messageId = 12345使元素排序

2 个答案:

答案 0 :(得分:2)

像@moteus所说,你的前提是不正确的:Lua表中的非数字条目没有排序。它们被定义的顺序通常与它们将被读取的顺序相同(例如,pairs将以任意顺序迭代这些条目)。分配新值不会以任何方式影响这一点。

答案 1 :(得分:0)

我想你可以使用table.sort,有一个简单的例子:

local tbl = {
    messageId = 0,
    timestamp = currentTime,
    responseStatus = {
        status = "FAILED",
        errorCode = "599",
        errorMessage = "problem"
    }
}

function fnCompare (e1, e2)
    -- you should promise e1 and e2 is tbl struct
    -- you can check e1 and e2 first by yourself
    return e1.messageId < e2.messageId;
end

-- test
local tbAll = {}
tbl.messageId = 3;
table.insert(tbAll, tbl);
-- add a another
table.insert(tbAll, {messageId = 1});
table.sort(tbAll, fnCompare);
for k, v in ipairs(tbAll) do
    print(v.messageId); -- result: 1 3
end