Useful and useless scripts

Some of my scripts for daily use on a linux desktop

Friday, February 18, 2011

HowTo run multiple Lua scripts in a Conky

Hello,

Here is a little HOWTO for running more than one Lua script at the same time.


1. Method for two scripts with Conky objects

This can be done for two scripts with the two functions of Conky : lua_draw_hook_pre and lua_draw_hook_post


lua_load /home/wlourf/lua/scriptA.lua
lua_draw_hook_pre functionA

lua_load /home/wlourf/lua/scriptB.lua
lua_draw_hook_post functionB


lua_draw_hook_pre is called before Conky parse the TEXT section and lua_draw_hook_post is called after the Conky parse the TEXT section. So effects are not very nice because the two calls are not synchronized.




2. Method with a Lua script for 2 or more scripts

Now, here is an example for 2 scripts, but you can modify it for three, four ... scripts :
Save the two scripts (scriptA.lua with conky_functionA() and scriptB.lua with conky_functionB() in the same folder : /home/wlourf/multi/ for my example :
Create a third script loadAll.lua, and paste that :

package.path = "/home/wlourf/multi/?.lua"
require 'scriptA' --for scriptA.lua ".lua" is not required here
require 'scriptB'

function conky_main()
conky_functionA()
conky_functionB()
end


and in the conkyrc, call the conky_main function with lua_draw_hook_pre or lua_draw_hook_post, like this :

lua_draw_hook_post main



3. With some variables

Now, sometimes, we need to use the same parameters in more than one script (colours, x and y position ...). So we have to write them in the conky_main() function so they can be used in the functions conky_functionA() and conky_functionB()

To avoid memory leaks, we have to declare the variables in local, so these variables will be available only for the conky_main() function, then we have to "pass" them to the functions, like that :

function conky_main()
local varX = 25
local varY = 50
conky_functionA(varX,varY)
conky_functionB(varX,varY)
end



and in the functions :
function conky_functionA(varX,varY)
table_config ={...,
x=varX,
y=varY,..
}
end



Ok, passing functions from the conky_main() function to other functions can be boring when we have a lot of parameters. The easiest way to pass the parameters is to group them into a table and to pass the table :
function conky_main()
local table_param={
varX = 25,
varY = 50
}
conky_functionA(table_param)
conky_functionB(table_param)
end


and in the functions :
function conky_functionA(t)
table_config ={...,
x=t.varX,
y=t.varY, ...
}
end


t.varX is the variable varX from the table t, it can be written t.["varX"]

That's all. I hope this little HowTo will help you to use multiple Lua scripts. This is my own way to manage multiple scripts, it can be done with others methods dofile, loadfile or instances !

Happy Conkying ;-)