John Kiragu
John Kiragu

Reputation: 121

Update Elements in table without changing table order Lua

I'd like to maintain the order of a table when updating table values in Lua.

Example

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

meaning tbl.messageId = 12345 leaves the elements ordered

Upvotes: 1

Views: 1227

Answers (2)

上山老人
上山老人

Reputation: 462

I suppose you can use table.sort, there is a simple example:

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

Upvotes: 0

tarleb
tarleb

Reputation: 22609

Like @moteus said, your premise is incorrect: non-numeric entries in Lua tables are not sorted. The order, in which they are defined won't, in general, be the same order as that in which they will be read (e.g., pairs will iterate over those entries in an arbitrary order). Assigning a new value will not affect this in any way.

Upvotes: 2

Related Questions