Prz*_*000 3 indexing lua lua-table
我有问题; 我必须在表格中查看我的程序中的一个字段.
if(launchArgs.androidIntent.extras.notification.custom.test_field ~= nil)then...
Run Code Online (Sandbox Code Playgroud)
当这个索引存在时一切正常,但是当它不存在时,我收到一个错误:
Attempt to index field 'notification' (a nil value).
Run Code Online (Sandbox Code Playgroud)
这是可以理解的.如何检查该索引是否存在?
试试这个
if (launchArgs and launchArgs.androidIntent and launchArgs.androidIntent.extras
and launchArgs.androidIntent.extras.notification and launchArgs.androidIntent.extras.notification.custom
and launchArgs.androidIntent.extras.notification.custom.test_field) then
-- do you stuff
end
Run Code Online (Sandbox Code Playgroud)
此代码将检查是否已设置每个表.
如果你确定启动args.androidIntent.extras总是设置你可以这样做
if(launchArgs.androidIntent.extras.notification and launchArgs.androidIntent.extras.notification.custom and launchArgs.androidIntent.extras.notification.custom.test_field)then
-- do your stuff
end
Run Code Online (Sandbox Code Playgroud)
或者只是使用这个函数,我在其他答案中发布(在这里也有帮助)
function IndexScan(input,value,case,_type)
if (input and type(input) == 'table') then
if (_type) then
if (type(value) == _type and value == input) then
return true;
end
else
if (type(value) == 'table' and value == input) then
return true;
end
end
for key,object in pairs(input) do
if (case and type(input)=='string' and type(key)=='string') then
if (_type) then
if (value:lower() == key:lower() and type(object)==_type) then
return true;
elseif(type(object)=='table') then
return IndexScan(object,value,case,_type)
end
else
if (value:lower() == key:lower()) then
return true;
elseif(type(object)=='table') then
return IndexScan(object,value,case,_type)
end
end
else
if (_type) then
if (key == value and type(object)==_type) then
return true
elseif(type(object)=='table') then
return IndexScan(object,value,case,_type)
end
else
if (key == value) then
return true
elseif(type(object)=='table') then
return IndexScan(object,value,case,_type)
end
end
end
end
end
return false;
end
-- IndexScan(@param table(table), @param index(string), @param case-sensitive(true/false), @param type (index type, string/boolean/number/table ...))
-- checks if these two indexes were set any where in the launchArgs table and checks their type
if (IndexScan(launchArgs,"notification",false,"table") and IndexScan(launchArgs,"test_field",false,"string")) then
-- do your stuff
end
Run Code Online (Sandbox Code Playgroud)
编辑: 修复了函数中的一些错误.
编辑: 在作者修复了通知错误后更新了脚本.