view src/luan/interp/LenExpr.java @ 31:5cf15507d77e

separate interpreter from interface git-svn-id: https://luan-java.googlecode.com/svn/trunk@32 21e917c8-12df-6dd8-5cb6-c86387c605b9
author fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9>
date Thu, 13 Dec 2012 02:50:04 +0000
parents b7d7069fee58
children e51906de0f11
line wrap: on
line source

package luan.interp;

import luan.Lua;
import luan.LuaNumber;
import luan.LuaTable;
import luan.LuaException;


final class LenExpr extends UnaryOpExpr {

	LenExpr(Expr op) {
		super(op);
	}

	@Override public Object eval(LuaStateImpl lua) throws LuaException {
		return new LuaNumber( length(op.eval(lua)) );
	}

	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" );
	}
}