This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm that you accept these cookies being set.

lua table
#1
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,
Reply
#2
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
Reply
#3
Many Thanks
Reply


Forum Jump: