Lua代码的奇怪行为(AwesomeWM配置)

在我的 rc.lua 文件(AwesomeWM 的配置文件)中添加以下代码,可以得到下面图片中所示的效果:

mybattmon = wibox.widget.textbox()
function battery_status ()
  local output={}
  local fd=io.popen("acpi", "r")
  local line=fd:read()
  while line do
    local battery_load = string.match(line, "(%d*)%%")
    local discharging
    if string.match(line, "Discharging")=="Discharging"
    then
      discharging="-"
    elseif string.match(line, "Charging")=="Charging"
      then
      discharging="⚡"
    else
      discharging=""
    end
--    if tonumber(battery_load) < 10 then fontColor="red" else fontColor="black" end
--    table.insert(output,"<span color='" ..fontColor.. "'>")
    table.insert(output,discharging.. "" ..battery_load.. "%")
--    table.insert(output,"</span>")
    line=fd:read() --读取下一行
  end
  return table.concat(output,"|") --使用竖线分隔电池信息
end
my_battmon_timer = timer({ timeout = 2 })
my_battmon_timer:connect_signal("timeout", function()
  mybattmon:set_markup( '<span background="#92B0A0" font="' .. font .. '"color="#000">BAT: ' .. battery_status() .. '</span>' )
end)
my_battmon_timer:start()

Good

如果取消对三行代码的注释(它们旨在在电池少于10%时改变颜色),则会得到以下结果:

Wrong

垂直线用于分隔第二个电池的位置。

有人知道为什么取消注释后,会在文本前后插入垂直线吗?

点赞
用户258523
用户258523

当表格中有超过一个元素时,您需要插入管道符。

您原始的代码如下(适用于单个电池的情况):

local output={}
table.insert(output, "a")
print(table.concat(output, "|"))
# a

您未注释的代码实际上是:

local output={}
table.insert(output, "pre-a")
table.insert(output, "a")
table.insert(output, "post-a")
print(table.concat(output, "|"))
# pre-a|a|post-a

您想将跨度字符串格式化为表格中的一个条目。

if tonumber(battery_load) < 10 then fontColor="red" else fontColor="black" end
local batstr = "<span color='" ..fontColor.. "'>"
batstr = batstr..discharging.. "" ..battery_load.. "%"
batstr = batstr.."</span>"
table.insert(output,batstr)
2015-05-19 18:38:49