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
Combine pcall() with assert() like…
…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.
If pcall returns as a success, and a proper value was given, then it just uses that. Otherwise, it replaces with your ‘none’ result.
Edit — same thing, just strike that, reverse it:
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:
https://www.tutorialspoint.com/lua/lua_error_handling.htm