comparison 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
comparison
equal deleted inserted replaced
774:3e30cf310e56 775:1a68fc55a80c
1 package luan;
2
3 import java.util.Map;
4 import java.util.Iterator;
5
6
7 public final class LuanPropertyMeta extends LuanMeta {
8 public static final LuanPropertyMeta INSTANCE = new LuanPropertyMeta();
9
10 private LuanPropertyMeta() {}
11
12 public LuanTable getters(LuanTable tbl) {
13 return (LuanTable)tbl.getMetatable().rawGet("get");
14 }
15
16 public LuanTable setters(LuanTable tbl) {
17 return (LuanTable)tbl.getMetatable().rawGet("set");
18 }
19
20 protected String type(LuanTable tbl) {
21 return (String)tbl.getMetatable().rawGet("type");
22 }
23
24 @Override public Object __index(LuanState luan,LuanTable tbl,Object key) throws LuanException {
25 Object obj = getters(tbl).rawGet(key);
26 if( obj == null )
27 return null;
28 if( !(obj instanceof LuanFunction) )
29 throw new LuanException("get for '"+key+"' isn't a function");
30 LuanFunction fn = (LuanFunction)obj;
31 return fn.call(luan);
32 }
33
34 @Override protected Iterator keys(final LuanTable tbl) {
35 return new Iterator() {
36 final Iterator<Map.Entry<Object,Object>> iter = getters(tbl).rawIterator();
37
38 @Override public boolean hasNext() {
39 return iter.hasNext();
40 }
41 @Override public Object next() {
42 return iter.next().getKey();
43 }
44 @Override public void remove() {
45 throw new UnsupportedOperationException();
46 }
47 };
48 }
49
50
51 @Override public boolean canNewindex() {
52 return true;
53 }
54
55 @Override public void __new_index(LuanState luan,LuanTable tbl,Object key,Object value) throws LuanException {
56 Object obj = setters(tbl).rawGet(key);
57 if( obj == null ) {
58 tbl.rawPut(key,value);
59 return;
60 }
61 if( !(obj instanceof LuanFunction) )
62 throw new LuanException("set for '"+key+"' isn't a function");
63 LuanFunction fn = (LuanFunction)obj;
64 fn.call(luan,new Object[]{value});
65 }
66
67 @Override public LuanTable newMetatable() {
68 LuanTable mt = super.newMetatable();
69 mt.rawPut( "get", new LuanTable() );
70 mt.rawPut( "set", new LuanTable() );
71 mt.rawPut( "type", "property" );
72 return mt;
73 }
74
75 }