我正在使用 AwesomeWM v4.0-170-g6c24848-dirty,针对 Lua 5.3.3 编译;我开始自定义我的小部件。
其中之一是时钟,技术上是 wibox.widget.textclock()
。我已经能够更改 format
以更改顺序,添加自定义消息,例如“今天是星期日,2017 年 7 月 23 日”,但是......没有关于序数的线索。
我这里的意思是如何将“rd”添加到 23rd,并使其根据当前日期更改为例如 21st,22 或 24。
我尝试在格式之前添加一个 ordinal
变量,然后是一个 if-else 语句以确定其值取决于日期。然而,这不起作用:我既不能在函数外“使用”日期格式,也不能在 format
内实现变量。
据我所知,字符串中的变量可以像下面的例子一样实现:
print("Hello ".. name .. ", key ".. k .. "的值为 ".. v .. "!")
但是,这在这里不起作用。我的线索用完了,你能给我点灯吗?
到目前为止,我已经编写了通用的“th”日期格式:
mytextclock = wibox.widget.textclock("%a %dth %B, %H:%M ", 60)
...其输出将是:dayoftheweek dayth month, HH, MM。
最佳答案
背景:
起初我考虑了两个选项来布置问题:
<强>1。从整个输出字符串中选择日期:程序处理后,使用某种 Bash echo $2
(考虑像 dayoftheweek day month hh:mm
这样的输出)在 Lua 中等价于...
<强>2。对待变量 day
从一开始就单独:这意味着找到一种方法来获取变量而不使用整个字符串,一旦我们拥有它......
...稍后用 if-else
处理它会根据其值改变输出的结构。
出于速度原因,我采用了第二种方式。我发现从一开始就获取变量更容易、更清晰,而不是将一些代码行用于从输出中提取。
所以我开始使用 %d
作为我工作的主要变量,它在 Lua 中用于表示日期中的日期。 (source)
这里主要是转换%d
的内容成一个字符串:
day = "%d" -- This is supposed to be an integer now.
daynumber = tostring(day) -- Converts it to a string.
lastdigit = tostring(day, -1)
print(lastdigit) -- Output: d.
砰!失败。这行不通,我希望有人可以在评论中说出原因。如果我打印最新的字符 (-1),则输出始终为 d,如果我尝试使用 -2,我将获得全天值。
我的主要理论基于事实分类:
a = "%d"
print(a)
在 Lua 解释器中(在你的 shell 中是 $ lua
)只返回 %d
, 根本没有整数;但这只是一个假设。更重要的是,据我所知%d
在日期上下文中使用,而不是独立作为变量的值。
可能的解决方案:
day = os.date("%d") -- First of all we grab the day from the system time.
-- As Lua displays the day with two digits, we are storing both of them in variables in order to process them separately later.
firstdigit = string.sub(day, 0, 1)
lastdigit = string.sub(day, -1)
-- We don't want Awesome to display '01st August' or '08th September'. We are going to suppress the '0'.
if firstdigit == "0" then
day = lastdigit
end
-- Now we want to display the day with its respective ordinal: 1st, 2nd, 3rd, 4th... we are going to process the last digit for this.
if lastdigit == "1" then
ordinal = "st"
elseif lastdigit == "2" then
ordinal = "nd"
elseif lastdigit == "3" then
ordinal = "rd"
else
ordinal = "th"
end
-- Finally, we display the final date.
mytextclock = wibox.widget.textclock(" %a " ..day..ordinal.. " %B %H:%M ", 60)
...所以我们得到以下输出:
关于linux - 如何对 AwesomeWM 文本时钟小部件实现序数日?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45264679/