Page 1 of 1

.filter pattern and functions

Posted: Thursday 14 September 2017 14:04
by emme
Ciao,

I'm approaching dzVents and it's simply fantastic...

I have a doubt about the .forEach function and the search pattern in case of browsing common devices...

example...
I have my BLE devices that have the profix NUT_ so, at the moment I found them with

Code: Select all

domoticz.devices().forEach(function(device)
            if (device.name:sub(1,4) == 'NUT_') then
but I'm wondering there is the possibility to use or create a different way like

Code: Select all

domoticz.devices().forEach(device).filter(.name:sub(1,4) == "NUT_')

is it possible... and if so how, to create function within the Execute section?

like

Code: Select all

function retTrue():
   return true

print(tostring(retTrue))
thanks
ciao
M

Re: .filter pattern and functions

Posted: Thursday 14 September 2017 14:55
by dannybloe
You have to turn it around. First you do the filter and with the filtered results you do the forEach:

Code: Select all

domoticz.devices()
	.filter(function(device)
		return (device.name:sub(1,4) == 'NUT_')
	end
	.forEach(function(device)
		-- do something with device
	end
The filter function returns list that you can use in combination with .reduce or .forEach. forEach doesn't return anything so there the 'chain' ends.

And your other question:
You can create functions anywhere in the module:

Code: Select all


local myFuncA = function()
	-- do something
end

return {
	execute = function(domoticz, device)
		local myFuncB = function()
			-- do something else
		end
		
		-- call the functions
		myFuncA()
		myFuncB()
	
	end
}

Just don't forget to declare all your functions and variables as locals so they don't interfere with other modules.