view core/src/luan/impl/LenExpr.java @ 404:d55e873e1f0d

metatables now only apply to tables
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 29 Apr 2015 07:04:40 -0600
parents 3dcb0f9bee82
children d9df6d6cb927
line wrap: on
line source

package luan.impl;

import luan.Luan;
import luan.LuanTable;
import luan.LuanFunction;
import luan.LuanException;
import luan.LuanSource;
import luan.LuanBit;


final class LenExpr extends UnaryOpExpr {

	LenExpr(LuanSource.Element se,Expr op) {
		super(se,op);
	}

	@Override public Object eval(LuanStateImpl luan) throws LuanException {
		Object o = op.eval(luan);
		if( o instanceof String ) {
			String s = (String)o;
			return s.length();
		}
		if( o instanceof byte[] ) {
			byte[] a = (byte[])o;
			return a.length;
		}
		LuanBit bit = luan.bit(se);
		if( !(o instanceof LuanTable) )
			throw bit.exception( "attempt to get length of a " + Luan.type(o) + " value" );
		LuanTable t = (LuanTable)o;
		LuanFunction fn = bit.getHandlerFunction("__len",t);
		if( fn != null )
			return Luan.first(bit.call(fn,"__len",new Object[]{o}));
		return t.length();
	}
}