Finally followed up this idea from a year ago. Using countexecstack to check the recursion depth for an L-system interpreter with no memory issues! I posted this already to
codegolf.stackexchange.com, but it's probably more valuable here.
This program makes an enormous Dragon curve.
%!
[ %The Dragon Curve
/X{X + Y F} % productions
/Y{F X - Y} %
/I{F X} % initial production
/A 90 % angle
/R 1 % radius
/b 70 % recursion bound
>>begin
/T[ %The Turtle
/F{R 0 rlineto
%currentpoint stroke moveto flushpage % uncomment to preview
}
/+{A rotate}
/-{A neg rotate}
>>def
[ %The Engine
/a countexecstack % base execstack size
/z{countexecstack a b add lt } % execstack size within bounds
/t{T exch 2 copy known{get exec}{pop pop}ifelse} % try turtle command
/s{
{ % try
load % lookup
} stopped { % failed to lookup
t % try turtle
}{ % succeeded in lookup
dup type/arraytype eq{ % if it's an array (ie. a procedure)
{ % iterate through it
z{ % within bounds
s % recursively expand (or descend)
}{ % exceeded bounds
t % try turtle
}ifelse
}forall
}{ % not an array
exec % simply execute it
}ifelse
}ifelse
}
>>begin
300 400 moveto
/I s stroke
showpage