Mark Munsterman
Mark Munsterman

Reputation: 169

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

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?

Upvotes: 4

Views: 10125

Answers (1)

Lucas S.
Lucas S.

Reputation: 332

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.

Upvotes: 4

Related Questions