view src/luan/lib/HtmlLib.java @ 60:a68ccb7aaa9c

implement setting java field values git-svn-id: https://luan-java.googlecode.com/svn/trunk@61 21e917c8-12df-6dd8-5cb6-c86387c605b9
author fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9>
date Mon, 07 Jan 2013 05:41:59 +0000
parents 8ede219cd111
children f86e4f77ef32
line wrap: on
line source

package luan.lib;

import luan.LuanState;
import luan.LuanTable;
import luan.LuanJavaFunction;


public final class HtmlLib {

	public static void register(LuanState luan) {
		LuanTable module = new LuanTable();
		LuanTable global = luan.global();
		global.put("html",module);
		try {
			add( module, "encode", String.class );
		} catch(NoSuchMethodException e) {
			throw new RuntimeException(e);
		}
	}

	private static void add(LuanTable t,String method,Class<?>... parameterTypes) throws NoSuchMethodException {
		t.put( method, new LuanJavaFunction(HtmlLib.class.getMethod(method,parameterTypes),null) );
	}

	public static String encode(String s) {
		char[] a = s.toCharArray();
		StringBuilder buf = new StringBuilder();
		for( int i=0; i<a.length; i++ ) {
			char c = a[i];
			switch(c) {
			case '&':
				buf.append("&amp;");
				break;
			case '<':
				buf.append("&lt;");
				break;
			case '>':
				buf.append("&gt;");
				break;
			case '"':
				buf.append("&quot;");
				break;
			default:
				buf.append(c);
			}
		}
		return buf.toString();
	}

}