diff src/luan/interp/IndexExpr.java @ 35:e51906de0f11

implement metatables git-svn-id: https://luan-java.googlecode.com/svn/trunk@36 21e917c8-12df-6dd8-5cb6-c86387c605b9
author fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9>
date Tue, 18 Dec 2012 07:05:58 +0000
parents
children 2a35154aec14
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/luan/interp/IndexExpr.java	Tue Dec 18 07:05:58 2012 +0000
@@ -0,0 +1,40 @@
+package luan.interp;
+
+import luan.Lua;
+import luan.LuaException;
+import luan.LuaTable;
+import luan.LuaFunction;
+
+
+final class IndexExpr extends BinaryOpExpr {
+
+	IndexExpr(Expr op1,Expr op2) {
+		super(op1,op2);
+	}
+
+	@Override public Object eval(LuaStateImpl lua) throws LuaException {
+		return index(lua,op1.eval(lua),op2.eval(lua));
+	}
+
+	private static Object index(LuaStateImpl lua,Object t,Object key) throws LuaException {
+		Object h;
+		if( t instanceof LuaTable ) {
+			LuaTable tbl = (LuaTable)t;
+			Object value = tbl.get(key);
+			if( value != null )
+				return value;
+			h = Utils.getHandlerObject("__index",t);
+			if( h==null )
+				return null;
+		} else {
+			h = Utils.getHandlerObject("__index",t);
+			if( h==null )
+				throw new LuaException( "attempt to index a " + Lua.type(t) + " value" );
+		}
+		if( h instanceof LuaFunction ) {
+			LuaFunction fn = (LuaFunction)h;
+			return Utils.first(fn.call(lua,t,key));
+		}
+		return index(lua,h,key);
+	}
+}