如何根据当前日期对 Lua 中的 table 进行排序

How to sort a table in Lua based on current date

我需要一个数组,它将以今天的日期作为第一个元素,并按该顺序对所有其他元素进行排序。

self.dayw=tonumber(os.date("%w")) --today's date
this is the array I have already implemented
 self.dayArray[1]=response["monday"]
 self.dayArray[2]=response["tuesday"]
 self.dayArray[3]=response["wednesday"]
 self.dayArray[4]=response["thursday"]
 self.dayArray[5]=response["friday"]
 self.dayArray[6]=response["saturday"]
 self.dayArray[7]=response["sunday"]

所以如果今天是星期五,我需要那个从星期五开始的数组作为第一个元素。

我已经创建了 sortArray={} 并尝试根据日期用元素填充它,但是代码太“忙”了,可能有更聪明的解决方案。如果可以,请帮忙。

一周中的每一天都分配了一个编号,从星期日 1 开始,到星期六 7 结束。为了找到当前日期的这个数字表示,调用 os.date("*t"),其中 returns 一个 table 填充了有关当前日期、月份、年份等的信息。此 table对应当天的数字称为wday.

for k, v in pairs(os.date("*t")) do
    print(k, v)
end

输出:

year    2020
wday    6
month   8
isdst   true
hour    21
day 28
sec 13
yday    241
min 48

这里,键wday关联的值为6,对应星期五。

有了这个数字,您可以通过在当天之前弹出元素然后在最后重新插入它们来重新排序 table 天。

-- Local references to table functions.
local tblins = table.insert
local tblrmv = table.remove

local days = {
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
}

local function reorder(days, wday)
    for i = wday - 1, 1, -1 do
        -- Pop element days[1] and then append it.
        tblins(days, tblrmv(days, 1))
    end
    return
end

local date_table = os.date("*t")
reorder(days, date_table.wday)

for i, day in ipairs(days) do
    print(i, day)
end

输出:

1   Friday
2   Saturday
3   Sunday
4   Monday
5   Tuesday
6   Wednesday
7   Thursday

如果您想要一个易于重新启动table 的版本,这里是我现有解决方案的扩展:

-- Local references to table functions.
local tblins = table.insert
local tblrmv = table.remove
local tblsrt = table.sort

-- The field `day' refers to the string representation; `num' refers to the
-- given day's original position in the table, which is used to restore the
-- table to its starting order.
local days = {
    {day = "Sunday", num = 1},
    {day = "Monday", num = 2},
    {day = "Tuesday", num = 3},
    {day = "Wednesday", num = 4},
    {day = "Thursday", num = 5},
    {day = "Friday", num = 6},
    {day = "Sunday", num = 7}
}

local function sort_days(left_day, right_day)
    return left_day.num < right_day.num
end

-- The reorder function remains the same
-- To put the days table back in its original order, call the following:
tblsrt(days, sort_days)

for i, day in ipairs(days) do
    print(i, day.day, day.num)
end

输出:

1   Sunday  1
2   Monday  2
3   Tuesday 3
4   Wednesday   4
5   Thursday    5
6   Friday  6
7   Saturday    7