diff core/src/luan/impl/IndexExpr.java @ 171:3dcb0f9bee82

add core component git-svn-id: https://luan-java.googlecode.com/svn/trunk@172 21e917c8-12df-6dd8-5cb6-c86387c605b9
author fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9>
date Sun, 22 Jun 2014 05:41:22 +0000
parents src/luan/impl/IndexExpr.java@4eaee12f6c65
children d55e873e1f0d
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/core/src/luan/impl/IndexExpr.java	Sun Jun 22 05:41:22 2014 +0000
@@ -0,0 +1,41 @@
+package luan.impl;
+
+import luan.Luan;
+import luan.LuanException;
+import luan.LuanTable;
+import luan.LuanFunction;
+import luan.LuanSource;
+
+
+final class IndexExpr extends BinaryOpExpr {
+
+	IndexExpr(LuanSource.Element se,Expr op1,Expr op2) {
+		super(se,op1,op2);
+	}
+
+	@Override public Object eval(LuanStateImpl luan) throws LuanException {
+		return index(luan,op1.eval(luan),op2.eval(luan));
+	}
+
+	private Object index(LuanStateImpl luan,Object t,Object key) throws LuanException {
+		Object h;
+		if( t instanceof LuanTable ) {
+			LuanTable tbl = (LuanTable)t;
+			Object value = tbl.get(key);
+			if( value != null )
+				return value;
+			h = luan.getHandler("__index",t);
+			if( h==null )
+				return null;
+		} else {
+			h = luan.getHandler("__index",t);
+			if( h==null )
+				throw luan.bit(op1.se()).exception( "attempt to index '"+op1.se().text()+"' (a " + Luan.type(t) + " value)" );
+		}
+		if( h instanceof LuanFunction ) {
+			LuanFunction fn = (LuanFunction)h;
+			return Luan.first(luan.bit(se).call(fn,"__index",new Object[]{t,key}));
+		}
+		return index(luan,h,key);
+	}
+}