Get the return codes. Look at the mcErrorCheck.lua module. It is all the return codes and examples of how to use it are commented out at the top. The return code you got was not 40. It was -40. Instead of using the mcErrorCheck module you can also use the API call mcCntlGetErrorString as in the example below.
This is an example of what has worked well for me. I'm not going to a label. I run a function that does what I want and immediately after returning to the calling function I exit (return) that function. At that point there is nothing else in that script executed. But everything after that is wrapped in functions so something has to call them for them to run. If I had lines of code after that function that were not in a function, they would be executed.
if (rc ~= 0) then
msg = mc.mcCntlGetErrorString(inst, rc) --Get the returned error string
errorOut(msg)
return --Exit the function
end
local function errorOut(msg)
local inst = mc.mcGetInstance()
mc.mcSpindleSetDirection(inst, mc.MC_SPINDLE_OFF)
mc.mcCntlMacroAlarm(inst, 3, msg)
end