Logic Machine Forum
lua table - Printable Version

+- Logic Machine Forum (https://forum.logicmachine.net)
+-- Forum: LogicMachine eco-system (https://forum.logicmachine.net/forumdisplay.php?fid=1)
+--- Forum: Scripting (https://forum.logicmachine.net/forumdisplay.php?fid=8)
+--- Thread: lua table (/showthread.php?tid=4180)



lua table - benanderson_475 - 08.08.2022

i have table for some lua code for porting to mqtt like the below

knx_cfg = {  
               ['3']  = {tag = 'Lounge Main', dim_ = true, knx_sw = '1/2/1', knx_sw_fb = '1/3/1', knx_dim = '1/4/1', knx_dim_fb = '1/5/1'},
                ['5'] = {tag = 'Lounge Seating', dim_ = true, knx_sw = '1/2/2', knx_sw_fb = '1/3/2', knx_dim = '1/4/2', knx_dim_fb = '1/5/2'},
              }
                   
if i check if for key that exists in table eg ['3'] or ['5'] all is well 
                            
                              if knx_cfg['3'].dim_ then
                                log( knx_cfg[3].dim_)
                                end

if i l check for a key that doesn't exist i get an error "attempt to index a nil value" which is expected as it doesn't exist

all i want to know is if the check for the key element [] i am looking for which is dynamic by other code exists in the table before next process, i was trying to not have a loop through 
the table 

is there another way?

Many Thanks,


RE: lua table - admin - 08.08.2022

You can check like this:
Code:
if knx_cfg['3'] and knx_cfg['3'].dim_ then
  log( knx_cfg[3].dim_)
end

Or a more strict check:
Code:
if type(knx_cfg['3']) == 'table' and knx_cfg['3'].dim_ then
  log( knx_cfg[3].dim_)
end



RE: lua table - benanderson_475 - 08.08.2022

Many Thanks