Re: How to check for key existence in a table (for the lazy programmer) ?
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: How to check for key existence in a table (for the lazy programmer) ?
- From: Andrew Starks <andrew.starks@...>
- Date: 2015年1月31日 12:12:36 -0600
On Saturday, January 31, 2015, Bertrand Mansion <
lua@mamasam.net> wrote:
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 ?
Another way is to use a vararg function:
local function pindex(tbl, key, ...)
tbl = tbl[key]
If (...) then
If type(tbl) == "table" then
return pindex(tbl, ...)
else
return nil, tbl, key
end
else
return true, tbl
end
end
local success, value, failed_at = pindex(my_table, "foo", "bar", "baz")
(iPhone + Gmail is not awesome as a code editor. Ymmv. Also, others may have a faster way)