Alejandro DC
Alejandro DC

Reputation: 236

Strange behaviour of lua code (AwesomeWM config)

With this piece of code in my rc.lua (configuration file of AwesomeWM) I get what you see in image bellow:

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()

Good

If I uncomment the three commented lines (which are meant to change the colour when the battery goes down to less than 10%), I get the following:

Wrong

The vertical bar is there to separate when I put my second battery.

Does somebody understand why the three lines changing the colour would make it insert the bars before and after the text?

Upvotes: 1

Views: 233

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80951

You are inserting the pipes when the table has more than one element.

Your original code is effectively this (for the single battery case):

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

Your uncommented version of the code is effectively this:

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

You want to format the span string as one entry in the table.

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)

Upvotes: 2

Related Questions