comparison 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
comparison
equal deleted inserted replaced
774:3e30cf310e56 775:1a68fc55a80c
1 package luan.modules;
2
3 import java.io.IOException;
4 import java.util.Arrays;
5 import java.util.Collections;
6 import luan.Luan;
7 import luan.LuanState;
8 import luan.LuanTable;
9 import luan.LuanFunction;
10 import luan.LuanJavaFunction;
11 import luan.LuanException;
12
13
14 public final class PackageLuan {
15
16 public static final LuanFunction requireFn;
17 static {
18 try {
19 requireFn = new LuanJavaFunction(PackageLuan.class.getMethod("require",LuanState.class,String.class),null);
20 } catch(NoSuchMethodException e) {
21 throw new RuntimeException(e);
22 }
23 }
24
25 public static LuanTable loaded(LuanState luan) {
26 LuanTable tbl = (LuanTable)luan.registry().get("Package.loaded");
27 if( tbl == null ) {
28 tbl = new LuanTable();
29 luan.registry().put("Package.loaded",tbl);
30 }
31 return tbl;
32 }
33
34 public static Object require(LuanState luan,String modName) throws LuanException {
35 Object mod = load(luan,modName);
36 if( mod==null )
37 throw new LuanException( "module '"+modName+"' not found" );
38 return mod;
39 }
40
41 public static Object load(LuanState luan,String modName) throws LuanException {
42 LuanTable loaded = loaded(luan);
43 Object mod = loaded.rawGet(modName);
44 if( mod == null ) {
45 if( modName.startsWith("java:") ) {
46 mod = JavaLuan.load(luan,modName.substring(5));
47 } else {
48 String src = read(luan,modName);
49 if( src == null )
50 return null;
51 LuanFunction loader = Luan.load(src,modName);
52 mod = Luan.first(
53 loader.call(luan,new Object[]{modName})
54 );
55 if( mod == null ) {
56 mod = loaded.rawGet(modName);
57 if( mod != null )
58 return mod;
59 throw new LuanException( "module '"+modName+"' returned nil" );
60 }
61 }
62 loaded.rawPut(modName,mod);
63 }
64 return mod;
65 }
66
67 static String read(LuanState luan,String uri) throws LuanException {
68 LuanTable t = IoLuan.uri(luan,uri,null);
69 if( t == null )
70 return null;
71 LuanFunction existsFn = (LuanFunction)t.get(luan,"exists");
72 boolean exists = (Boolean)Luan.first(existsFn.call(luan));
73 if( !exists )
74 return null;
75 LuanFunction reader = (LuanFunction)t.get(luan,"read_text");
76 return (String)Luan.first(reader.call(luan));
77 }
78
79 }