I have this dictionary below. I would like to move the 3rd index into first place. How would I do so?
local myTable = {
{name = "Fun", day = 5},
{name = "Boring", day = 6},
{name = "Tired", day = 7} -- I want to move this to the first index
}
I have this dictionary below. I would like to move the 3rd index into first place. How would I do so?
local myTable = {
{name = "Fun", day = 5},
{name = "Boring", day = 6},
{name = "Tired", day = 7} -- I want to move this to the first index
}
Hello!
I am going to link some Developer forums that can possibly help you with your problem at hand.
Hope this helps!
Use table.sort
local myTable = {
{name = "Fun", day = 5},
{name = "Boring", day = 6},
{name = "Tired", day = 7} -- I want to move this to the first index
}
table.sort(myTable, function(cur, nextItr)
return cur["day"] > nextItr["day"]
end)
You can use table.insert
to insert a new element at the beginning of a table.
If you want to move the element from the third index to the first index, you can use table.remove
to remove it from where it is and table.insert
to insert it at the beginning.
<My code is below.
local myTable = {
{name = “Fun”, day = 5},
{name = “Boring”, day = 6},
{name = “Tired”, day = 7} – I want to move this to the first index
}
– Print the contents of the table
for i,v in pairs(myTable) do
print(i,v)
end
local temp = myTable[3] – Store the 3rd index
myTable[3] = myTable[2] – Assign the second index to the third index
myTable[2] = myTable[1] – Assign the first index to the second index
myTable[1] = temp – Assign the 3rd index to the first index
– Print the contents of the table
for i,v in pairs(myTable) do
print(i,v)
end
Use table.insert
{name = "Fun", day = 5},
{name = "Boring", day = 6},
{name = "Tired", day = 7}
}
table.insert(myTable, 1, myTable[3])
table.remove(myTable, 4)