view src/luan/interp/ReturnStmt.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 1e37f22a34c8
children e3624b7cd603
line wrap: on
line source

package luan.interp;

import luan.Lua;
import luan.LuaException;
import luan.LuaFunction;


final class ReturnStmt implements Stmt {
	private final Expressions expressions;
	private final Expr tailFnExpr;
	boolean throwReturnException = true;

	ReturnStmt(Expressions expressions) {
		if( expressions instanceof FnCall ) {  // tail call
			FnCall fnCall = (FnCall)expressions;
			this.expressions = fnCall.args;
			this.tailFnExpr = fnCall.fnExpr;
		} else {
			this.expressions = expressions;
			this.tailFnExpr = null;
		}
	}

	@Override public void eval(LuaStateImpl lua) throws LuaException {
		lua.returnValues = expressions.eval(lua);
		if( tailFnExpr != null ) {
			LuaFunction tailFn = Lua.checkFunction( tailFnExpr.eval(lua) );
			if( tailFn instanceof LuaClosure ) {
				lua.tailFn = (LuaClosure)tailFn;
			} else {
				lua.returnValues =  tailFn.call(lua,lua.returnValues);
			}
		}
		if( throwReturnException )
			throw new ReturnException();
	}
}