I feel like this should be simple, but can't seem to solve it. I have a function in Lua that's designed to validate a confirm code in a survey. Basically, if the ID is valid, then we can grab lots of data from that code, but if it's not a valid code, the script will break because it'll be populating nil values.
So, I basically need an error check — if the function can run properly, then run it. If it can't then I need to ask for a new code.
I've tried using pcall which feels like is exactly for this. I'm working off the Lua documentation:
if pcall(foo) then
-- no errors while running `foo'
...
else
-- `foo' raised an error: take appropriate actions
...
end
On my end, that means I have a function:
function populate()
... doing lots here to unencrypt and parse the ID someone gives and populate variables
end
Then I'm running the follwing:
if pcall(populate) then
print('no errors!') -- Just printing as a test, if there's no error, I'll run the script
else
print('Oh snap theres an error!) -- I'll change this to ask the user for a valid ID and then try again
end
What am I missing? I know it's going to be simple. But the last part of my code always returns the "Oh snap..." no matter what.
Thanks in advance, I have a super complex code running that I was able to build from just reading responses to other questions, but can't seem to get this simple part to work. Entirely possible I'm missing the point of pcall.
What do you expect?
If i am unsure what happen or which return value i should use for another condition i normally test/check in Lua Standalone...
€ lua
Lua 5.4.4 Copyright (C) 1994-2022 Lua.org, PUC-Rio
> pcall(string.gsub,'foo','%l','bar') -- Check for lowercases
true barbarbar 3
> pcall(string.gsub,'foo','%u','bar') -- Check for uppercases
true foo 0
> -- In this case i have to use maybe the third return value to decide what to do?
> -- OK -- Lets go...
> a, b, c = pcall(string.gsub,'foo','%u','bar') -- Check for uppercases
> if a and c == 0 then print('Only Kiddies here!') return false end
Only Kiddies here!
false
>