view core/src/luan/impl/FnCall.java @ 419:8fbb961aabd5

improve repr() to check metamethod recursively
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 30 Apr 2015 23:15:40 -0600
parents d55e873e1f0d
children b48cfa14ba60
line wrap: on
line source

package luan.impl;

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


final class FnCall extends CodeImpl implements Expressions {
	final Expr fnExpr;
	final Expressions args;
	final String fnName;

	FnCall(LuanSource.Element se,Expr fnExpr,Expressions args) {
		super(se);
		this.fnExpr = fnExpr;
		this.args = args;
		this.fnName = fnExpr.se().text();
	}

	@Override public Object eval(LuanStateImpl luan) throws LuanException {
		return call( luan, fnExpr.eval(luan) );
	}

	private Object call(LuanStateImpl luan,Object o) throws LuanException {
		if( o instanceof LuanFunction ) {
			LuanFunction fn = (LuanFunction)o;
			return luan.bit(se).call( fn, fnName, Luan.array(args.eval(luan)) );
		}
		if( o instanceof LuanTable ) {
			LuanTable t = (LuanTable)o;
			Object h = t.getHandler("__call");
			if( h != null )
				return call(luan,h);
		}
		throw luan.bit(fnExpr.se()).exception( "attempt to call '"+fnExpr.se().text()+"' (a " + Luan.type(o) + " value)" );
	}

	@Override public String toString() {
		return "(FnCall "+fnName+" "+fnExpr+" "+args+")";
	}
}