lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I think it is possible to prepare this test on previous assignement.
Otherwise only I see this solution:

local function eval( chunk )
  local f = load('return '..chunk)
  local ok, ret = pcall(f)
  return ok and ret or nil
end

local v = eval' host.devices.bridge.friendlyName'
if v then
  ...
end

Charles

> -----Message d'origine-----
> De : lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org] De
> la part de Bertrand Mansion
> Envoyé : samedi 31 janvier 2015 11:45
> À : Lua mailing list
> Objet : How to check for key existence in a table (for the lazy
> programmer)?
> 
> In Lua programs, I often see code like the following:
> 
>   if host.devices and host.devices.bridge and
> host.devices.bridge.friendlyName then
> 
> In Php, I have seen this:
> 
>   if (isset($host['devices']['bridge']['friendlyName']))
> 
> 
> In Python, I have seen this:
> 
>   try:
>     if host['devices']['bridge']['friendlyName']:
>       ...
>   except KeyError:
>     pass
> 
> Are there other ways in Lua to check for a key existence ?