Mercurial Hosting > luan
diff src/luan/lib/StringLib.java @ 119:f1bf2890d80f
support String methods
git-svn-id: https://luan-java.googlecode.com/svn/trunk@120 21e917c8-12df-6dd8-5cb6-c86387c605b9
author | fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9> |
---|---|
date | Sun, 01 Jun 2014 09:38:40 +0000 |
parents | 8c706d6eb5dc |
children | f537ff5e511d |
line wrap: on
line diff
--- a/src/luan/lib/StringLib.java Sun Jun 01 07:07:31 2014 +0000 +++ b/src/luan/lib/StringLib.java Sun Jun 01 09:38:40 2014 +0000 @@ -9,6 +9,7 @@ import luan.LuanJavaFunction; import luan.LuanElement; import luan.LuanException; +import luan.MetatableGetter; public final class StringLib { @@ -17,6 +18,7 @@ public static final LuanFunction LOADER = new LuanFunction() { @Override public Object call(LuanState luan,Object[] args) { + luan.addMetatableGetter(mg); LuanTable module = new LuanTable(); try { add( module, "to_binary", String.class ); @@ -44,6 +46,42 @@ t.put( method, new LuanJavaFunction(StringLib.class.getMethod(method,parameterTypes),null) ); } + private static final LuanTable mt = new LuanTable(); + static { + try { + add( mt, "__index", LuanState.class, String.class, Object.class ); + } catch(NoSuchMethodException e) { + throw new RuntimeException(e); + } + } + + private static final MetatableGetter mg = new MetatableGetter() { + public LuanTable getMetatable(Object obj) { + return obj instanceof String ? mt : null; + } + }; + + public static Object __index(LuanState luan,final String s,Object key) throws LuanException { + LuanTable mod = (LuanTable)luan.global().get("String"); + if( mod!=null ) { + Object obj = mod.get(key); + if( obj instanceof LuanFunction ) { + final LuanFunction fn = (LuanFunction)obj; + return new LuanFunction() { + @Override public Object call(LuanState luan,Object[] args) throws LuanException { + Object[] a = new Object[args.length+1]; + a[0] = s; + System.arraycopy(args,0,a,1,args.length); + return fn.call(luan,a); + } + }; + } + } + if( luan.global().get("Java") != null ) + return JavaLib.__index(luan,s,key); + return null; + } + static int start(String s,int i) { return i==0 ? 0 : i > 0 ? i - 1 : s.length() + i; }