Lua不会覆盖空值

我有一个可能返回结果或不返回结果的sql语句。如果它没有返回结果,我需要将空值改为"none"。我似乎无法弄清楚如何做到这一点。我已经将我的代码放在了pcall中,但仍无法被覆盖。我在if语句行中始终收到"attempt to index a nil value"的错误。我在Debian 8上运行lua 5.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
点赞
用户11740758
用户11740758

将pcall()与assert()结合起来,就像这样...

如果 pcall(assert,SqlConnect(number).status) 成功,则返回 true,否则返回 false

...然后在 true 或 false 部分执行必要的操作。 比如说,如果你需要这个值,则在 true 部分进行 pcall() 以获取该值,并在 false 部分执行回滚情况。

2020-12-07 22:33:16
用户3342050
用户3342050

如果 pcall 成功返回一个合适的值,它会直接使用这个值。否则,它会替换成你设置的 'none' 结果。

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

我不确定,但如果我必须猜测,那就是它失败的原因。

https://riptutorial.com/lua/example/16000/using-pcall


以下是转换成 xpcall 的方法:

function try()
    attempt = SqlConnect( number ) .status or 'none'  --  如果为 nil,则替换为 'none'
    if attempt == '' then attempt = 'none' end  --  将空字符串替换为 'none'
    return attempt
end

function except()  --  如果对 `SqlConnect( number )` 的调用完全失败
    return 'none'
end

success, result = xpcall( try, except )

https://www.tutorialspoint.com/lua/lua_error_handling.htm

2020-12-07 23:37:19