diff src/luan/modules/PackageLuan.java @ 775:1a68fc55a80c

simplify dir structure
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 26 Aug 2016 14:36:40 -0600
parents core/src/luan/modules/PackageLuan.java@647602e8291a
children c49980cdece6
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/luan/modules/PackageLuan.java	Fri Aug 26 14:36:40 2016 -0600
@@ -0,0 +1,79 @@
+package luan.modules;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import luan.Luan;
+import luan.LuanState;
+import luan.LuanTable;
+import luan.LuanFunction;
+import luan.LuanJavaFunction;
+import luan.LuanException;
+
+
+public final class PackageLuan {
+
+	public static final LuanFunction requireFn;
+	static {
+		try {
+			requireFn = new LuanJavaFunction(PackageLuan.class.getMethod("require",LuanState.class,String.class),null);
+		} catch(NoSuchMethodException e) {
+			throw new RuntimeException(e);
+		}
+	}
+
+	public static LuanTable loaded(LuanState luan) {
+		LuanTable tbl = (LuanTable)luan.registry().get("Package.loaded");
+		if( tbl == null ) {
+			tbl = new LuanTable();
+			luan.registry().put("Package.loaded",tbl);
+		}
+		return tbl;
+	}
+
+	public static Object require(LuanState luan,String modName) throws LuanException {
+		Object mod = load(luan,modName);
+		if( mod==null )
+			throw new LuanException( "module '"+modName+"' not found" );
+		return mod;
+	}
+
+	public static Object load(LuanState luan,String modName) throws LuanException {
+		LuanTable loaded = loaded(luan);
+		Object mod = loaded.rawGet(modName);
+		if( mod == null ) {
+			if( modName.startsWith("java:") ) {
+				mod = JavaLuan.load(luan,modName.substring(5));
+			} else {
+				String src = read(luan,modName);
+				if( src == null )
+					return null;
+				LuanFunction loader = Luan.load(src,modName);
+				mod = Luan.first(
+					loader.call(luan,new Object[]{modName})
+				);
+				if( mod == null ) {
+					mod = loaded.rawGet(modName);
+					if( mod != null )
+						return mod;
+					throw new LuanException( "module '"+modName+"' returned nil" );
+				}
+			}
+			loaded.rawPut(modName,mod);
+		}
+		return mod;
+	}
+
+	static String read(LuanState luan,String uri) throws LuanException {
+		LuanTable t = IoLuan.uri(luan,uri,null);
+		if( t == null )
+			return null;
+		LuanFunction existsFn = (LuanFunction)t.get(luan,"exists");
+		boolean exists = (Boolean)Luan.first(existsFn.call(luan));
+		if( !exists )
+			return null;
+		LuanFunction reader = (LuanFunction)t.get(luan,"read_text");
+		return (String)Luan.first(reader.call(luan));
+	}
+
+}