view src/luan/LuanState.java @ 1148:49fb4e83484f

webserver - change headers to lower case
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 04 Feb 2018 17:11:06 -0700
parents ba4daf107e07
children 7ef40e1923b7
line wrap: on
line source

package luan;

import java.io.Closeable;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import luan.impl.LuanCompiler;
import luan.modules.BasicLuan;
import luan.modules.JavaLuan;


public final class LuanState implements LuanCloneable {
	public LuanJavaOk javaOk;
	private Map registry;
	private final List<Reference<Closeable>> onClose = new ArrayList<Reference<Closeable>>();
	public boolean isLocked = false;

	public LuanState() {
		javaOk = new LuanJavaOk();
		registry = new HashMap();
	}

	private LuanState(LuanState luan) {}

	@Override public LuanState shallowClone() {
		return new LuanState(this);
	}

	@Override public void deepenClone(LuanCloneable dc,LuanCloner cloner) {
		LuanState clone = (LuanState)dc;
		clone.registry = cloner.clone(registry);
		clone.javaOk = (LuanJavaOk)cloner.clone(javaOk);
		if( cloner.type == LuanCloner.Type.INCREMENTAL )
			isLocked = true;
	}

	public Map registry() {
		return registry;
	}

	public void onClose(Closeable c) {
		onClose.add(new WeakReference<Closeable>(c));
	}

	public void close() throws IOException {
		for( Reference<Closeable> ref : onClose ) {
			Closeable c = ref.get();
			if( c != null )
				c.close();
		}
		onClose.clear();
	}

	public final Object eval(String cmd,Object... args) throws LuanException {
		return Luan.load(cmd,"eval").call(this,args);
	}
/*
	public final Object eval(String cmd,LuanTable env) throws LuanException {
		LuanFunction fn = BasicLuan.load(this,cmd,"eval",env,true);
		return fn.call(this);
	}
*/

	public String toString(Object obj) throws LuanException {
		if( obj instanceof LuanTable ) {
			LuanTable tbl = (LuanTable)obj;
			return tbl.toString(this);
		}
		if( obj == null )
			return "nil";
		if( obj instanceof Number )
			return Luan.toString((Number)obj);
		if( obj instanceof byte[] )
			return "binary: " + Integer.toHexString(obj.hashCode());
		return obj.toString();
	}

	public Object index(Object obj,Object key) throws LuanException {
		if( obj instanceof LuanTable ) {
			LuanTable tbl = (LuanTable)obj;
			return tbl.get(this,key);
		}
		if( obj != null && javaOk.ok )
			return JavaLuan.__index(this,obj,key);
		throw new LuanException("attempt to index a " + Luan.type(obj) + " value" );
	}

/*
	public Number checkNumber(Object obj) throws LuanException {
		if( obj instanceof Number )
			return (Number)obj;
		throw new LuanException( "attempt to perform arithmetic on '"+context()+"' (a " + Luan.type(obj) + " value)" );
	}
*/
}