【问题标题】:Strange behaviour of lua code (AwesomeWM config)lua 代码的奇怪行为(AwesomeWM 配置)
【发布时间】:2015-05-20 02:50:42
【问题描述】:

通过我的 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() --read next line
  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()

如果我取消注释三个注释行(当电池电量低于 10% 时更改颜色),我会得到以下信息:

当我放入第二块电池时,竖线可以分开。

有人明白为什么改变颜色的三行会使其在文本前后插入条吗?

【问题讨论】:

    标签: lua awesome-wm


    【解决方案1】:

    当表格包含多个元素时,您将插入管道。

    您的原始代码实际上是这样的(对于单电池盒):

    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)
    

    【讨论】:

    • table.concat 将连接字符串粘贴在表格的 每个 元素之间。您的表通常包含每个电池一个条目。未注释的代码在每个电池的表中添加了两个额外的条目。开始和结束跨度标签。因此table.concat 将管道粘贴在它们之间。用可见/可打印字符替换跨度,您会更清楚地看到问题。
    • 非常感谢!我不知道那是table.concat的功能,我认为它与table.insert相同但没有放置位置(即在末尾)。感谢您的解释。它奏效了。
    • table.insert 不需要职位(您不会在任何电话中给出职位)。 table.insert 不会返回任何东西,而 table.concat 显然会返回。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多