Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a lua-table if a key is present?

Tags:

lua

lua-table

Every minute I retrieve the following data from a webshop via a request.

  {
  ['action'] = 'all',
  ['orders'] = { ['order'] = { [1] = { ['locationId'] = 1,
                                       ['id'] = 93,
                                       ['orderNumber'] = '3200'
                                     }
                             }
               },
  ['status'] = 'success'
  }

From this table I need the ID number which I read with the code:

IdNummer = Table.orders.order[1].id;

If there is an order, this works

If no order is ready, I will receive the following table:

{ 
['action'] = 'all', 
['orders'] = { ['order'] = {}  }, 
['status'] = 'success'
}

Since "id" doesn't exist, I get the error: Attempt to index a nil value (field'?') How can I check if "id" exists without getting an error?

like image 513
Mark Munsterman Avatar asked Sep 17 '25 06:09

Mark Munsterman


1 Answers

You should first check that the entry Table.orders.order[1] exists before trying to access it's id field.

In lua an unassigned field has the nil value. So you can do:

local orders = Table.orders.order
local IdNummer = nil
if orders[1] ~= nil then
  IdNummer = orders[1].id;
end

Take care, in this example if the index doesn't exists IdNummer will have a nil value.

like image 73
Lucas S. Avatar answered Sep 19 '25 14:09

Lucas S.