view src/luan/Lua.java @ 35:e51906de0f11

implement metatables git-svn-id: https://luan-java.googlecode.com/svn/trunk@36 21e917c8-12df-6dd8-5cb6-c86387c605b9
author fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9>
date Tue, 18 Dec 2012 07:05:58 +0000
parents 8217d8485715
children 2a35154aec14
line wrap: on
line source

package luan;


public class Lua {
	public static final String version = "Luan 0.0";

	public static String type(Object obj) {
		if( obj == null )
			return "nil";
		if( obj instanceof String )
			return "string";
		if( obj instanceof Boolean )
			return "boolean";
		if( obj instanceof LuaNumber )
			return "number";
		return "userdata";
	}

	public static boolean toBoolean(Object obj) {
		return obj != null && !Boolean.FALSE.equals(obj);
	}

	public static String toString(Object obj) {
		if( obj == null )
			return "nil";
		return obj.toString();
	}

	public static String asString(Object obj) {
		if( obj instanceof String || obj instanceof LuaNumber )
			return obj.toString();
		return null;
	}

	public static String checkString(Object obj) throws LuaException {
		String s = asString(obj);
		if( s == null )
			throw new LuaException( "attempt to use a " + Lua.type(obj) + " as a string" );
		return s;
	}

	public static LuaNumber toNumber(Object obj) {
		if( obj instanceof LuaNumber )
			return (LuaNumber)obj;
		if( obj instanceof String ) {
			String s = (String)obj;
			try {
				return new LuaNumber( Double.parseDouble(s) );
			} catch(NumberFormatException e) {}
		}
		return null;
	}

	public static LuaNumber checkNumber(Object obj) throws LuaException {
		LuaNumber n = toNumber(obj);
		if( n == null )
			throw new LuaException( "attempt to perform arithmetic on a " + type(obj) + " value" );
		return n;
	}

	public static LuaFunction checkFunction(Object obj) throws LuaException {
		if( obj instanceof LuaFunction )
			return (LuaFunction)obj;
		throw new LuaException( "attempt to call a " + type(obj) + " value" );
	}

	public static LuaTable getMetatable(Object obj) {
		if( !(obj instanceof LuaTable) )
			return null;
		LuaTable table = (LuaTable)obj;
		return table.getMetatable();
	}

}