comparison core/src/luan/LuanBit.java @ 419:8fbb961aabd5

improve repr() to check metamethod recursively
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 30 Apr 2015 23:15:40 -0600
parents 91af5337b9ae
children b31d614343e8
comparison
equal deleted inserted replaced
418:455784e2227d 419:8fbb961aabd5
88 } 88 }
89 89
90 public String toString(Object obj) throws LuanException { 90 public String toString(Object obj) throws LuanException {
91 if( obj instanceof LuanTable ) { 91 if( obj instanceof LuanTable ) {
92 LuanTable tbl = (LuanTable)obj; 92 LuanTable tbl = (LuanTable)obj;
93 Object h = luan.getHandler("__tostring",tbl); 93 Object h = tbl.getHandler("__tostring");
94 if( h instanceof LuanMeta ) { 94 if( h instanceof LuanMeta ) {
95 LuanMeta meta = (LuanMeta)h; 95 LuanMeta meta = (LuanMeta)h;
96 return meta.__tostring(luan,tbl); 96 return meta.__tostring(luan,tbl);
97 } 97 }
98 LuanFunction fn = checkFunction(h); 98 LuanFunction fn = checkFunction(h);
101 } 101 }
102 return Luan.toString(obj); 102 return Luan.toString(obj);
103 } 103 }
104 104
105 public String repr(Object obj) throws LuanException { 105 public String repr(Object obj) throws LuanException {
106 if( obj instanceof LuanTable ) { 106 if( obj == null )
107 LuanFunction fn = getHandlerFunction("__repr",(LuanTable)obj); 107 return "nil";
108 if( fn != null ) 108 if( obj instanceof Boolean )
109 return checkString( Luan.first( call(fn,"__repr",new Object[]{obj}) ) ); 109 return Luan.toString((Boolean)obj);
110 } 110 if( obj instanceof Number )
111 String repr = Luan.repr(obj); 111 return Luan.toString((Number)obj);
112 if( repr==null ) 112 if( obj instanceof String )
113 throw exception( "value '" + obj + "' doesn't support repr()" ); 113 return "\"" + Luan.stringEncode((String)obj) + "\"";
114 return repr; 114 if( obj instanceof LuanRepr )
115 return ((LuanRepr)obj).repr(luan);
116 throw exception( "value '" + obj + "' doesn't support repr()" );
115 } 117 }
116 118
117 public LuanFunction getHandlerFunction(String op,LuanTable t) throws LuanException { 119 public LuanFunction getHandlerFunction(String op,LuanTable t) throws LuanException {
118 Object f = luan.getHandler(op,t); 120 Object f = t.getHandler(op);
119 if( f == null ) 121 if( f == null )
120 return null; 122 return null;
121 return checkFunction(f); 123 return checkFunction(f);
122 } 124 }
123 125