.filter pattern and functions

Easy to use, 100% Lua-based event scripting framework.

Moderator: leecollings

Post Reply
User avatar
emme
Posts: 909
Joined: Monday 27 June 2016 11:02
Target OS: Raspberry Pi / ODroid
Domoticz version: latest
Location: Milano, Italy
Contact:

.filter pattern and functions

Post 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
The most dangerous phrase in any language is:
"We always done this way"
dannybloe
Posts: 1355
Joined: Friday 29 August 2014 11:26
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Ermelo
Contact:

Re: .filter pattern and functions

Post 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.
Creator dzVents - RPi3, loads of zwave devices, esp8266, evohome.
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 1 guest