Lua不会覆盖nil值

Lua不会覆盖nil值,lua,Lua,我有一个sql语句,可以返回结果,也可以不返回。如果它不返回结果,我需要将nil值更改为“none”。我似乎不知道该怎么做。我已经把我的代码放在pcall中,但仍然不能被覆盖。我在if语句行中不断得到“尝试索引一个nil值”。我正在Debian8上运行Lua5.2.3。我错过了什么 --if ( SqlConnect(number).status == nil or SqlConnect(number).status == '') then if pcall( SqlConnect(number

我有一个sql语句,可以返回结果,也可以不返回。如果它不返回结果,我需要将nil值更改为“none”。我似乎不知道该怎么做。我已经把我的代码放在pcall中,但仍然不能被覆盖。我在if语句行中不断得到“尝试索引一个nil值”。我正在Debian8上运行Lua5.2.3。我错过了什么

--if ( SqlConnect(number).status == nil or SqlConnect(number).status == '') then
if pcall( SqlConnect(number).status ) then
    result = "none"
else
    result = SqlConnect(number).status
end
将pcall()与assert()组合,如

…然后做正确或错误部分中必须做的事情。
假设您需要该值,然后在true部分执行pcall(),以在false部分获取该值和回退案例。

如果pcall返回成功,并且给出了正确的值,则它只使用该值。否则,它将替换为“无”结果

local success, result = pcall( SqlConnect(number).status )

if not success or result == '' or type( result ) == nil then
    result = 'none'
end
编辑——同样的事情,只需敲打它,反转它:

if not success or type( result ) == nil or result == '' then

编辑:

pcall()可能只希望该函数作为参数,而不是附加的
.status

我不确定,但如果让我猜的话,这就是它失败的原因。


下面是您如何将其作为xpcall编写的:

function try()
    attempt = SqlConnect( number ) .status or 'none'  --  if nil, replace with 'none'
    if attempt == '' then attempt = 'none' end  --  replace blank strings with 'none'
    return attempt
end

function except()  --  if call to `SqlConnect( number )` completely fails
    return 'none'
end

success, result = xpcall( try, except )

我已经如上所述添加了assert片段,但仍在尝试索引nil值。我已经用一个有效的值对它进行了测试,它工作正常。我刚刚复制了你的pcall(assert)语句,字面上就是复制并粘贴到我的代码中,lua脚本在“if pcall”行失败。通过“尝试索引一个零值堆栈回溯”,我复制并粘贴了你的代码到我的脚本中,我在第一行得到了“尝试索引一个零值”。本地成功。。。。。。。。有值时,状态会打印出一个值。如果没有值,我只是想打印“none”。哦,是的,颠倒
=''
的顺序,它会在看到空白之前看到nil…它甚至不会到达if语句。它给了我本地成功线路上的错误。只是在DB上的一个值上测试了它,它工作得很好。这并不完全令人惊讶。过去我在xpcall方面取得了更好的成功。措辞有点不同,但似乎运行时没有崩溃,比pcall更好。你把它打开了吗?还没有。仍在尝试获取正确的语法。“result ret,err=xpcall(SqlConnect.status,debug.traceback);”对我不起作用。有几个问题:SqlConnect(number)返回什么类型?错误准确地抛出在哪里?什么类型是SqlConnect(数字)。状态?我们需要更多的信息来正确回答。
function try()
    attempt = SqlConnect( number ) .status or 'none'  --  if nil, replace with 'none'
    if attempt == '' then attempt = 'none' end  --  replace blank strings with 'none'
    return attempt
end

function except()  --  if call to `SqlConnect( number )` completely fails
    return 'none'
end

success, result = xpcall( try, except )