简体   繁体   English

conky 在 if 语句中使用 function 调用

[英]conky using a function call within an if statement

How do I call a function after loading it in conkyrc?在 conkyrc 中加载后如何调用 function? For example:例如:

I'm trying to get the active interface name which is returning properly我正在尝试获取正确返回的活动接口名称

${lua conky_findInterface} #gives me device name

function conky_findInterface()
  local handle = io.popen('ip a | grep "state UP" | cut -d: -f2 | tr -d " "')
  local result = handle:read('*a'):gsub('\n$','')
  handle:close()
  return result
end

How do I use it more dynamically?我如何更动态地使用它? Such as:如:

${if_up ${lua_parse "${lua conky_findInterface}"}} #this does not work nor do my other variations
Hello
${else}
Goodbye
${endif}

It seems that a conky if statement argument can't be a string, so a string returned by a Lua function won't work.似乎 conky if 语句参数不能是字符串,因此 Lua function 返回的字符串将不起作用。 For example, where my interface is "enp2s0", the statement ${if_up enp2s0} will work, but ${if_up "enp2s0"} will not.例如,如果我的界面是“enp2s0”,语句${if_up enp2s0}会起作用,但${if_up "enp2s0"}不会。

A workaround is to include the entire conky if statement in a Lua function. For example:解决方法是将整个 conky if 语句包含在 Lua function 中。例如:

function findInterface()
  local handle = io.popen('ip a | grep "state UP" | cut -d: -f2 | tr -d " "')
  local result = handle:read('*a'):gsub('\n$','')
  handle:close()
  return result
end

function conky_ifupInterface()
  local ifup = "${if_up " .. findInterface() .. "}"
  ifup = ifup .. "Hello${else}"
  ifup = ifup .. "Goodbye${endif}"
  return ifup
end

The function conky_ifupInterface() is then called in conkyrc with the line:然后在conkyrc中使用以下行调用 function conky_ifupInterface()

${lua_parse conky_ifupInterface}

Unfortunately, just returning the first line of the if statement isn't sufficient to satisfy the lua_parse operator.不幸的是,仅返回 if 语句的第一行不足以满足lua_parse运算符的要求。 The entire statement through the ${endif} has to be returned.必须返回通过${endif}的整个语句。

Note that the current implementation of findInterface will cause the conky config to crash on a call to conky_ifupInterface if the interface is down because findInterface will return a null value, resulting in the if statement beginning with ${if_up } .请注意,如果接口关闭, findInterface的当前实现将导致 conky 配置在调用conky_ifupInterface时崩溃,因为findInterface将返回 null 值,导致 if 语句以${if_up }开头。 To make it work for testing, I did the following quick and dirty bit...为了让它用于测试,我做了以下快速而肮脏的事情......

function findInterface()
  local handle = io.popen('ip a | grep "state UP" | cut -d: -f2 | tr -d " "')
  local result = handle:read('*a'):gsub('\n$','')
  handle:close()
  if result == "" then
    handle = io.popen('ip a | grep "state DOWN" | cut -d: -f2 | tr -d " "')
    result = handle:read('*a'):gsub('\n$','')
    handle:close()
  end
  return result
end

Yuck.呸。 I'm sure you can do better: :^)我相信你可以做得更好::^)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM