diff src/luan/interp/LengthExpr.java @ 2:4da26b11d12a

start interp git-svn-id: https://luan-java.googlecode.com/svn/trunk@3 21e917c8-12df-6dd8-5cb6-c86387c605b9
author fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9>
date Wed, 14 Nov 2012 08:53:25 +0000
parents
children 7a2cdbc5767f
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/luan/interp/LengthExpr.java	Wed Nov 14 08:53:25 2012 +0000
@@ -0,0 +1,30 @@
+package luan.interp;
+
+import luan.Lua;
+import luan.LuaNumber;
+import luan.LuaTable;
+import luan.LuaException;
+
+
+final class LengthExpr extends UnaryOpExpr {
+
+	LengthExpr(Expr op) {
+		super(op);
+	}
+
+	@Override Object eval() throws LuaException {
+		return new LuaNumber( length(op.eval()) );
+	}
+
+	private static int length(Object obj) throws LuaException {
+		if( obj instanceof String ) {
+			String s = (String)obj;
+			return s.length();
+		}
+		if( obj instanceof LuaTable ) {
+			LuaTable t = (LuaTable)obj;
+			return t.length();
+		}
+		throw new LuaException( "attempt to get length of a " + Lua.type(obj) + " value" );
+	}
+}