我有问题,我必须在我的程序检查一个字段在表中。
if(launchArgs.androidIntent.extras.notification.custom.test_field ~= nil)then...当这个索引存在时,一切都正常,但当它不存在时,我得到一个错误:
Attempt to index field 'notification' (a nil value).这是可以理解的。如何检查该索引是否存在?
发布于 2014-12-15 17:51:54
你可以用这个:
local function try(root, query)
local ids, len = {}, 0
for id in query:gmatch("%w+") do
len = len + 1
ids[len]= id
end
local node = root
for i=1,len do
if type(node) ~= 'table' then return nil end
node = node[ids[i]]
end
return node
end用法:
local tbl = { a = { b = { c = { d = 1 } } } }
print(try(tbl, 'a.b.c.d')) -- prints 1
print(try(tbl, 'a.b.c.x')) -- prints nil
print(try(tbl, 'a.x.c.d')) -- prints nilhttps://stackoverflow.com/questions/27488325
复制相似问题