Finding matched parentheses

David Epstein dfepstein at comcast.net
Thu Jul 25 20:17:20 EDT 2013


Has anyone scripted a function that will locate the closing  
parenthesis (or bracket, etc.) of a pair?  Below is my effort.   
Reports of its limitations or simpler alternatives (regex?) are invited.

David Epstein

function offsetPair a,b,str, at z
   -- returns offset(a,str) and loads in z offset(b,str) where b is  
the "matching" member of the pair;
   -- returns 0 if there is no a, empty if there is no match

   if a is not in str then return 0
   if b is not in str then return empty
   put 0 into b4 -- skipped characters
   put 0 into na -- number (ordinal) of the a hit
   put 0 into nb
   repeat
     put offset(a,str,b4) into ca -- character position of a
     put offset(b,str,b4) into cb -- character position of a
     if ca = 0 and na < nb then return empty
     if cb = 0 and nb < na then return empty
     -- only take note of the first hit:
     put empty into hitCase -- default
     if ca > 0 and (ca < cb or cb = 0) then put "a" into hitCase
     if cb > 0 and (cb < ca or ca = 0) then put "b" into hitCase
     if hitCase = "a" then
       add 1 to na
       put ca+b4 into aca[na] -- absolute char position of a hit  
number na
       put aca[na] into b4
     else if hitCase = "b" then
       add 1 to nb
       put cb+b4 into acb -- absolute char position of most recent b hit
       put acb into b4
     else return empty
     if na = nb then -- we have a match
       put acb into z
       return aca[1]
     end if
   end repeat
   return empty
end offsetPair




More information about the use-livecode mailing list