Mercurial Hosting > luan
view src/luan/modules/PackageLuan.java @ 897:821e4634b787
remove _reuseAddress
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Thu, 06 Oct 2016 23:52:53 -0600 |
parents | ea1768c00d03 |
children | 0d884377e923 |
line wrap: on
line source
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.LuanCloner; 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.equals(Boolean.FALSE) ) 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)); if( mod == null ) mod = Boolean.FALSE; } else { String src = read(luan,modName); if( src == null ) { mod = Boolean.FALSE; } else { 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)); */ IoLuan.LuanIn in = (IoLuan.LuanIn)t.rawGet("java"); try { if( !in.exists() ) return null; return in.read_text(); } catch(IOException e) { throw new LuanException(e); } } public static void enableLoad(LuanState luan,String... mods) throws LuanException { if( !luan.isLocked ) return; LuanTable loaded = loaded(luan); for( String mod : mods ) { if( loaded.rawGet(mod) == null ) { luan.isLocked = false; luan.deepenClone(luan,new LuanCloner(LuanCloner.Type.COMPLETE)); break; } } } }