Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I change the order of specific elements in a table?

Asked by 8 years ago

Ok so let's say I had a table like this:

local Test = {
    ["Anim1"] = {};
    ["Anim2"] = {};
    ["Anim3"] = {};
    ["Anim4"] = {};
}

How would I edit the table so that it looks more like this?

local Test = {
    ["Anim1"] = {};
    ["Anim3"] = {};
    ["Anim2"] = {};
    ["Anim4"] = {};
}

I attempted table.sort() but I couldn't quite figure it out. I don't really need code, a walkthrough would be good enough. Thanks!

0
Having a function attempt to locate the index seems a bit impossible. There technically isn't an index for any of those, so I have no idea how to approach this. Shawnyg 4330 — 8y

1 answer

Log in to vote
0
Answered by 8 years ago

If I understand correctly, you want to swap elements around in a table, I.E. element at index 1 swap positions with element at index 2.

You can do this with the below function, which I believe to be fairly easy to understand.

-- tbl -    Table the elements reside in
-- i1 - Index of the first object
-- i2 - Index of the second object
function swapElements(tbl, i1, i2)
    local v = tbl[i2]
    tbl[i2] = tbl[i1]
    tbl[i1] = v
end

So in a list consisting of 1, 2, 3 doing swapElements on index 1 and index 2 would produce 2,1,3

0
You're not fulfilling his question. He asking for a function similar to yours, but will FIND the index. Shawnyg 4330 — 8y
0
I'm not sure if I'm still following, surely the implementation of swapElements(table, "Anim2", "Anim3") would be what you're refering to when you say index. RightLegRed 15 — 8y
Ad

Answer this question