Page 1 of 1

Use of table.foreach for device name repetitions

Posted: Sunday 02 October 2022 22:02
by Wolly76
Hi all,

I would like to clean my code a bit by replacing

Code: Select all

local devicesThermostatTemperature = {'Thermostat (Room1) - Temperature', 'Thermostat (Room2) - Temperature', 'Thermostat (Room3) - Temperature', 'Thermostat (Room3) - Temperature'};
with

Code: Select all

local devicesThermostatNames = {'Room1', 'Room2', 'Room3', 'Room4'}
local devicesThermostatTemperature = {}; table.foreach(devicesThermostatNames,  function(k,v) table.insert(devicesThermostatTemperature,'Thermostat ('..v..') - Temperature') end )
at the start of the dzVents-script, i.e. before the "return {....}"
Except for Temperatures, there is a list of Setpoints and Valves as well, and this would make it easier to extend.

Unfortunately, I receive errors "2022-09-29 21:29:36.999 Error: dzVents: Error: (3.1.8) ...ipts/dzVents/generated_scripts/thermostatZoneControl.lua:4: attempt to call a nil value (field 'foreach')", which does not really surprise me but I was wondering if this might work anyhow? Just to note that the code works in a LUA online compiler.

Could this work, with a (small) code modification? Are there any better solutions to avoid these repetitions?

Thanks in advance. Looking forward.
/Wol

Re: Use of table.foreach for device name repetitions

Posted: Monday 03 October 2022 10:31
by mgugu
According to http://lua-users.org/wiki/TableLibraryTutorial, table.foreach is now deprecated. pair() operator is recommended instead.