1
Mach4 General Discussion / Proper way to error out of a lua function if an API call fails
« on: February 07, 2024, 07:27:23 AM »
OK.
So every
call that we see in macros like m6() etc are actually a
call, where "rc" is the return code that indicates API success or failure.
For some reason, all the scripts people write handwave this away and blithely assume that API calls always work.
That might very well be true in 99.999% of the cases, but it is poor programming practice to not check error codes.
That means that functions like m6() need an error-checking function within them, like this:
I'm talking to some lua experts elsewhere to see if there is a way to do something like
so as to make the syntax a little cleaner, and is seems that lua does not have a case or switch statement, so parsing all the various possible error codes is likely to be a bitch.
But it is worth discussing this: if an API call fails in a gCode replacement call like m6(), what should the function do to gracefully report the error to the user and stop the machine?
There has to be a best practice here.
Ideally there would be a global wc(rc) lua function that was written to do just that and came with Mach - maybe there is?
So every
Code: [Select]
variable = mc.mcGetSomething(inst)
call that we see in macros like m6() etc are actually a
Code: [Select]
variable, rc = mc.mcGetSomething(inst)
call, where "rc" is the return code that indicates API success or failure.
For some reason, all the scripts people write handwave this away and blithely assume that API calls always work.
That might very well be true in 99.999% of the cases, but it is poor programming practice to not check error codes.
That means that functions like m6() need an error-checking function within them, like this:
Code: [Select]
function m6()
function wc(rc) -- wc stands for "welfare check"
if (not(rc == mc.MERROR_NOERROR))
-- Do something reasonable to abort m6()
end
end
-- Do tool change stuff here
local inst, rc = mc.mcGetInstance()
wc(rc) -- make sure we got our instance
-- etc..
end
I'm talking to some lua experts elsewhere to see if there is a way to do something like
Code: [Select]
local inst, wc(rc) = mc.mcGetInstance()
so as to make the syntax a little cleaner, and is seems that lua does not have a case or switch statement, so parsing all the various possible error codes is likely to be a bitch.
But it is worth discussing this: if an API call fails in a gCode replacement call like m6(), what should the function do to gracefully report the error to the user and stop the machine?
There has to be a best practice here.
Ideally there would be a global wc(rc) lua function that was written to do just that and came with Mach - maybe there is?