diff src/luan/modules/parsers/LuanToString.java @ 1791:f8f5c51f5b36

xml work
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 26 Dec 2023 19:16:18 -0700
parents 582384548a69
children
line wrap: on
line diff
--- a/src/luan/modules/parsers/LuanToString.java	Mon Dec 25 23:07:59 2023 -0700
+++ b/src/luan/modules/parsers/LuanToString.java	Tue Dec 26 19:16:18 2023 -0700
@@ -79,6 +79,7 @@
 	private final Luan luan;
 	private final LuanFunction fnOptions;
 	private final LuanTable stack = new LuanTable();
+	private final Set<LuanTable> seen = new HashSet<LuanTable>();
 
 	public LuanToString() {
 		this.luan = null;
@@ -115,11 +116,11 @@
 
 	public String toString(Object obj) throws LuanException {
 		StringBuilder sb = new StringBuilder();
-		toString(obj,sb,0,settingsInit);
+		objectToString(obj,sb,0,settingsInit);
 		return sb.toString();
 	}
 
-	private void toString(Object obj,StringBuilder sb,int indented,Settings settings) throws LuanException {
+	private void objectToString(Object obj,StringBuilder sb,int indented,Settings settings) throws LuanException {
 		if( obj == null ) {
 			sb.append( "nil" );
 			return;
@@ -148,6 +149,12 @@
 	}
 
 	private void toString(LuanTable tbl,StringBuilder sb,int indented,Settings settings) throws LuanException {
+		if( !seen.add(tbl) ) {
+			if( settings.strict )
+				throw new LuanException("loop in "+tbl.rawToString());
+			sb.append("<loop>");
+			return;
+		}
 		if( tbl.getMetatable()!=null ) {
 			if( settings.strict )
 				throw new LuanException("can't handle metatables when strict");
@@ -207,7 +214,7 @@
 			} else {
 				indent(sb,indented+1);
 			}
-			toString(obj,sb,indented+1,settings);
+			objectToString(obj,sb,indented+1,settings);
 		}
 		for( Object obj : map.entrySet() ) {
 			Map.Entry entry = (Map.Entry)obj;
@@ -247,7 +254,7 @@
 			sb.append( (String)key );
 		} else {
 			sb.append( '[' );
-			toString( key, sb, indented, keySettings );
+			objectToString( key, sb, indented, keySettings );
 			sb.append( ']' );
 		}
 		sb.append( settings.compressed ? "=" : " = " );
@@ -257,7 +264,7 @@
 			settings = settings.cloneSettings();
 			settings.applyOptions(options);
 		}
-		toString( entry.getValue(), sb, indented, settings );
+		objectToString( entry.getValue(), sb, indented, settings );
 		stack.removeFromList(stack.rawLength());  // pop
 	}