1

I want to use custom variales in my Lua config of conky to share config between computers. Why does the following does not work, it uses simple Lua code:

conky.config={..}

-- set variables
work = "COMPUTERNAME"
lan  = "wlp9s0"
-- compare with current host name (conky's global variable)
if work == nodename then
  lan = "enp3s0"
end 

-- use $lan in conky's text
conky.text = [[${color yellow}$lan ${alignr}${addr wlp9s0}]]

I did not find any documentation or example how to use custom defined variables. $lan is not resolved and printed as ${lan}

Jens Peters
  • 2,075
  • 1
  • 22
  • 30

1 Answers1

4

Without using Conky, I'm going to make an answer based on some assumptions I've made after reading the various configuration sections found on the wiki.

It appears to me that the 'variables' one uses in the conky.text field, and other template fields, are not part of the Lua environment. That is to say, that the $ and ${} syntax probably does not perform environment lookups to interpolate values. This might also mean that the nodename variable you're comparing with is actually nil.

In any event, if your lan variable is not being interpolated, the quick fix is to simply concatenate your strings:

conky.text = [[${color yellow}]] .. lan.. [[ ${alignr}${addr wlp9s0}]]

Or consider writing your own string iterpolation function, if you want a cleaner looking string:

local function interp (s, t)
    return s:gsub('(#%b{})', function (w)
        return t[w:sub(3, -2)] or w
    end)
end

conky.text = interp([[${color yellow}#{lan} ${alignr}${addr wlp9s0}]], {
    lan = lan
})

Note, in the event that nodename is not part of the Lua environment, you can try using io.popen to run hostname manually, and then read from the file handle it returns.

Oka
  • 23,367
  • 6
  • 42
  • 53
  • Yes the interpolation hint did the trick. I am new to LUA maybe that was an fundamental misunderstanding of myself. Thank you. To complete your answer, first nodename is part of Conky and resolved to the correct value. Concatenating strings inside conky,text did not work for some unknown reason. What worked for me. I put my "if" statement at top of "conkyrc", define a template "template0=[[${color yellow}]] .. lan .. [[${alignr}${addr wlp9s0}]]" and use it in conky.text. Next problem is to solve "${addr wlp9s0}", as ${addr $lan} is not working. – Jens Peters Nov 03 '16 at 21:13
  • @JensPeters Is `nodename` an actual variable, in the sense that it is provided by the Lua environment - or is it simply a Conky 'variable', in the sense that it can be resolved by a template string? And again, `$lan` won't work because Conky doesn't search your Lua [environment](http://www.lua.org/manual/5.3/manual.html#2.2) for variables. You can do `'${addr' .. lan .. '}'`, or some other concatenation solution. I can update my question in a bit, to give you a clearer understanding of environments. – Oka Nov 03 '16 at 21:39