view core/src/luan/impl/EqExpr.java @ 576:4723d22062ce

remove LuanBit
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 13 Jul 2015 20:38:26 -0600
parents b48cfa14ba60
children 859c0dedc8b6
line wrap: on
line source

package luan.impl;

import java.util.Arrays;
import luan.Luan;
import luan.LuanFunction;
import luan.LuanTable;
import luan.LuanException;
import luan.LuanElement;


final class EqExpr extends BinaryOpExpr {

	EqExpr(LuanElement el,Expr op1,Expr op2) {
		super(el,op1,op2);
	}

	@Override public Object eval(LuanStateImpl luan) throws LuanException {
		return eq(luan);
	}

	private boolean eq(LuanStateImpl luan) throws LuanException {
		Object o1 = op1.eval(luan);
		Object o2 = op2.eval(luan);
		if( o1 == o2 || o1 != null && o1.equals(o2) )
			return true;
		if( o1 instanceof Number && o2 instanceof Number ) {
			Number n1 = (Number)o1;
			Number n2 = (Number)o2;
			return n1.doubleValue() == n2.doubleValue();
		}
		if( o1 instanceof byte[] && o2 instanceof byte[] ) {
			byte[] b1 = (byte[])o1;
			byte[] b2 = (byte[])o2;
			return Arrays.equals(b1,b2);
		}
		if( !(o1 instanceof LuanTable && o2 instanceof LuanTable) )
			return false;
		LuanTable t1 = (LuanTable)o1;
		LuanTable t2 = (LuanTable)o2;
		LuanTable mt1 = t1.getMetatable();
		LuanTable mt2 = t2.getMetatable();
		if( mt1==null || mt2==null )
			return false;
		Object f = mt1.rawGet("__eq");
		if( f == null || !f.equals(mt2.rawGet("__eq")) )
			return false;
		luan.push(el,"__eq");
		try {
			LuanFunction fn = luan.checkFunction(f);
			return luan.checkBoolean( Luan.first(fn.call(luan,new Object[]{o1,o2})) );
		} finally {
			luan.pop();
		}
	}

	@Override public String toString() {
		return "(EqExpr "+op1+" "+op2+")";
	}
}