Mercurial Hosting > luan
diff src/luan/LuanPropertyMeta.java @ 775:1a68fc55a80c
simplify dir structure
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Fri, 26 Aug 2016 14:36:40 -0600 |
parents | core/src/luan/LuanPropertyMeta.java@cdc70de628b5 |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/luan/LuanPropertyMeta.java Fri Aug 26 14:36:40 2016 -0600 @@ -0,0 +1,75 @@ +package luan; + +import java.util.Map; +import java.util.Iterator; + + +public final class LuanPropertyMeta extends LuanMeta { + public static final LuanPropertyMeta INSTANCE = new LuanPropertyMeta(); + + private LuanPropertyMeta() {} + + public LuanTable getters(LuanTable tbl) { + return (LuanTable)tbl.getMetatable().rawGet("get"); + } + + public LuanTable setters(LuanTable tbl) { + return (LuanTable)tbl.getMetatable().rawGet("set"); + } + + protected String type(LuanTable tbl) { + return (String)tbl.getMetatable().rawGet("type"); + } + + @Override public Object __index(LuanState luan,LuanTable tbl,Object key) throws LuanException { + Object obj = getters(tbl).rawGet(key); + if( obj == null ) + return null; + if( !(obj instanceof LuanFunction) ) + throw new LuanException("get for '"+key+"' isn't a function"); + LuanFunction fn = (LuanFunction)obj; + return fn.call(luan); + } + + @Override protected Iterator keys(final LuanTable tbl) { + return new Iterator() { + final Iterator<Map.Entry<Object,Object>> iter = getters(tbl).rawIterator(); + + @Override public boolean hasNext() { + return iter.hasNext(); + } + @Override public Object next() { + return iter.next().getKey(); + } + @Override public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + + + @Override public boolean canNewindex() { + return true; + } + + @Override public void __new_index(LuanState luan,LuanTable tbl,Object key,Object value) throws LuanException { + Object obj = setters(tbl).rawGet(key); + if( obj == null ) { + tbl.rawPut(key,value); + return; + } + if( !(obj instanceof LuanFunction) ) + throw new LuanException("set for '"+key+"' isn't a function"); + LuanFunction fn = (LuanFunction)obj; + fn.call(luan,new Object[]{value}); + } + + @Override public LuanTable newMetatable() { + LuanTable mt = super.newMetatable(); + mt.rawPut( "get", new LuanTable() ); + mt.rawPut( "set", new LuanTable() ); + mt.rawPut( "type", "property" ); + return mt; + } + +}