@@ -169,7 +169,12 @@ MacroFunctionDef::evaluateMFunction(Evaluator* eval, const ArrayOfVector& inputs
169169
170170 uint64 tic = 0 ;
171171 try {
172- insertLocalFunctions (context);
172+ // Only insert local functions on first entry (they don't change during recursion).
173+ if (recursionDepth == 1 ) {
174+ insertLocalFunctions (context);
175+ } else if (this ->nextFunction != nullptr || this ->prevFunction != nullptr ) {
176+ insertLocalFunctions (context);
177+ }
173178 setInputArgumentNames (context, inputs);
174179 bindInputs (context, inputs);
175180 context->getCurrentScope ()->setNargOut (nargout);
@@ -202,12 +207,15 @@ MacroFunctionDef::evaluateMFunction(Evaluator* eval, const ArrayOfVector& inputs
202207
203208 outputs = prepareOutputs (context, nargout);
204209
205- onCleanup (eval);
206-
210+ if (!cleanupTasks.empty ()) {
211+ onCleanup (eval);
212+ }
207213 context->popScope ();
208214 eval->callstack .popDebug ();
209215 } catch (const Exception&) {
210- onCleanup (eval);
216+ if (!cleanupTasks.empty ()) {
217+ onCleanup (eval);
218+ }
211219 if (recursionDepth == 1 && tic != 0 ) {
212220 internalProfileFunction stack
213221 = computeProfileStack (eval, getCompleteName (), this ->getFilename (), false );
@@ -283,12 +291,26 @@ MacroFunctionDef::evaluateMScript(Evaluator* eval, const ArrayOfVector& inputs,
283291ArrayOfVector
284292MacroFunctionDef::evaluateFunction (Evaluator* eval, const ArrayOfVector& inputs, int nargout)
285293{
286- lock ();
287- updateCode ();
288- if (isScript) {
289- return evaluateMScript (eval, inputs, nargout);
294+ // Skip lock/updateCode on recursive calls � code cannot change mid-recursion.
295+ static thread_local int evaluateFunctionDepth = 0 ;
296+ if (evaluateFunctionDepth == 0 ) {
297+ lock ();
298+ updateCode ();
299+ }
300+ ++evaluateFunctionDepth;
301+ ArrayOfVector result;
302+ try {
303+ if (isScript) {
304+ result = evaluateMScript (eval, inputs, nargout);
305+ } else {
306+ result = evaluateMFunction (eval, inputs, nargout);
307+ }
308+ } catch (...) {
309+ --evaluateFunctionDepth;
310+ throw ;
290311 }
291- return evaluateMFunction (eval, inputs, nargout);
312+ --evaluateFunctionDepth;
313+ return result;
292314}
293315// =============================================================================
294316std::string
0 commit comments