skip to Main Content

I have an sql statement that could return a result or not. If it doesn’t return a result I need to change the nil value to "none". I cant seem to figure out how to do this. I have put my code in pcall can still wont get overwritten. I keep getting "attempt to index a nil value" in the if statement line. I am running lua 5.2.3 on Debian 8. What am I missing?

--if ( SqlConnect(number).status == nil or SqlConnect(number).status == '') then
if pcall( SqlConnect(number).status ) then
    result = "none"
else
    result = SqlConnect(number).status
end

2

Answers


  1. Combine pcall() with assert() like…

    if pcall(assert,SqlConnect(number).status) then return true else return false end
    

    …then do what you have to do in the true or false section.
    Lets say you need the value then do your pcall() in the true section to get the value and the fallback case in the false section.

    Login or Signup to reply.
  2. If pcall returns as a success, and a proper value was given, then it just uses that. Otherwise, it replaces with your ‘none’ result.

    local success, result = pcall( SqlConnect(number).status )
    
    if not success or result == '' or type( result ) == nil then
        result = 'none'
    end
    

    Edit — same thing, just strike that, reverse it:

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

    Edit:

    pcall() probably wants just that function as an arg, and not the appended .status.
    I’m not certain, but if I had to guess, that’s why it was failing.
    https://riptutorial.com/lua/example/16000/using-pcall


    Here’s how’d you’d write it as an 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 )
    

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search