view core/src/luan/LuanPropertyMeta.java @ 416:91af5337b9ae

add LuanMeta.__tostring()
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 30 Apr 2015 06:28:25 -0600
parents ce8e19567911
children 23a93c118042
line wrap: on
line source

package luan;

import java.util.Map;
import java.util.Iterator;


public final class LuanPropertyMeta extends LuanMeta {
	public static final LuanPropertyMeta INSTANCE = new LuanPropertyMeta();

	private LuanPropertyMeta() {}

	public LuanTable getters(LuanTable tbl) {
		return (LuanTable)tbl.getMetatable().get("get");
	}

	public LuanTable setters(LuanTable tbl) {
		return (LuanTable)tbl.getMetatable().get("set");
	}

	protected String type(LuanTable tbl) {
		return (String)tbl.getMetatable().get("type");
	}

	@Override public Object __index(LuanState luan,LuanTable tbl,Object key) throws LuanException {
		Object obj = getters(tbl).get(key);
		if( obj == null )
			return null;
		if( !(obj instanceof LuanFunction) )
			throw luan.exception("get for '"+key+"' isn't a function");
		LuanFunction fn = (LuanFunction)obj;
		return luan.call(fn);
	}

	@Override protected Iterator keys(final LuanTable tbl) {
		return new Iterator() {
			final Iterator<Map.Entry<Object,Object>> iter = getters(tbl).iterator();

			@Override public boolean hasNext() {
				return iter.hasNext();
			}
			@Override public Object next() {
				return iter.next().getKey();
			}
			@Override public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}


	@Override public boolean canNewindex() {
		return true;
	}

	@Override public void __newindex(LuanState luan,LuanTable tbl,Object key,Object value) throws LuanException {
		Object obj = setters(tbl).get(key);
		if( obj == null )
			throw luan.exception("can't set property '"+key+"'");
		if( !(obj instanceof LuanFunction) )
			throw luan.exception("set for '"+key+"' isn't a function");
		LuanFunction fn = (LuanFunction)obj;
		luan.call(fn,new Object[]{value});
	}

	@Override public LuanTable newMetatable() {
		LuanTable mt = super.newMetatable();
		mt.put( "get", new LuanTable() );
		mt.put( "set", new LuanTable() );
		mt.put( "type", "property" );
		return mt;
	}

}