ceedebee wrote:Is it posible to call another lua file or function from this script? Or is it posible to include functions in an other file into a lua script?
It certainly is. But if Your reason for that is only to make your time-script more organized You can do something like this instead:
Code: Select all
-- script_time_misc.lua
-------------------------------------
commandArray = {}
local function runEvery5min()
-- Put your script code here that shall run every 5 minutes
-- Below is an example using nested tables commandarray and a random delay
-- commandArray[#commandArray + 1]={['My Device']='Off AFTER '..math.random(10,50) }
end
local function runEvery10min()
-- Put your script code here that shall run every 10 minutes
end
local function runEvery30min()
-- Put your script code here that shall run every 30 minutes
end
local function runEvery60min()
-- Put your script code here that shall run every 60 minutes
end
local m = os.date('%M')
if (m % 5 == 0) then
runEvery5min()
end
if (m % 10 == 0) then
runEvery10min()
end
if (m % 30 == 0) then
runEvery30min()
end
if (m % 60 == 0) then
runEvery60min()
end
return commandArray
But if you have functions or variables that you want to define in one single place and then call from multiple Lua scripts it makes sense to put them in a module like this:
First create the commonly used script file, the "module". In this example we call it myFunctions.lua
Put it in your Lua scripts folder.
Code: Select all
-----------------------------------------------------------------------------
-- myFunctions.lua: A module with various functions aimed for Domoticz
local mf = {} -- Public namespace
mf.HELLO = "Hello world" -- Just an example
function mf.blinkLight(light, times)
times = times or 2
local cmd1 = 'Off'
local cmd2 = 'On'
local pause = 0
if (otherdevices[light] == 'Off') then
cmd1 = 'On'
cmd2 = 'Off'
end
for i = 1, times do
commandArray[#commandArray + 1]={[light]=cmd1..' AFTER '..pause }
pause = pause + 3
commandArray[#commandArray + 1]={[light]=cmd2..' AFTER '..pause }
pause = pause + 3
end
end
return mf
Then, in your ordinary device-script or time-script you can use the functions (or variables) like this:
Code: Select all
if (devicechanged["My Button"]) then
local mf = require("scripts/lua/myFunctions")
print(mf.HELLO)
mf.blinkLight("My Living Room Light")
end
ONLY IF YOU ARE NOT ON A RASPBERRY PI
Note: The require statement
local mf = require("scripts/lua/myFunctions") will probably only work on Raspberry Pi. If You are running Domoticz on a different distribution you must help Lua to find the path of your Lua scripts folder.
In that case put this line before the line with the require statement
Code: Select all
package.path = "/usr/local/domoticz/scripts/lua/?.lua;"..package.path
You should of course replace
/usr/local/domoticz/scripts/lua/ with whatever the actual lua script name folder path is on your installation.