changeset 794:f16c77ef0f4f

add Parsers.json_string and Thread.global
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 05 Sep 2016 16:08:00 -0600
parents 60661a8e738c
children dd36eae6aa04
files src/luan/modules/Parsers.luan src/luan/modules/Thread.luan src/luan/modules/ThreadLuan.java
diffstat 3 files changed, 59 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/src/luan/modules/Parsers.luan	Mon Sep 05 15:19:44 2016 -0600
+++ b/src/luan/modules/Parsers.luan	Mon Sep 05 16:08:00 2016 -0600
@@ -9,7 +9,8 @@
 M.bbcode_to_html = BBCode.toHtml
 M.bbcode_to_text = BBCode.toText
 M.csv_to_list = Csv.toList
-M.json_parse = Json.parse
+M.json_parse = Json.parse  -- converts json string to luan object
+M.json_string = Json.toString  -- converts luan object to json string
 M.theme_to_luan = Theme.toLuan
 
 return M
--- a/src/luan/modules/Thread.luan	Mon Sep 05 15:19:44 2016 -0600
+++ b/src/luan/modules/Thread.luan	Mon Sep 05 16:08:00 2016 -0600
@@ -1,9 +1,36 @@
 java()
 local ThreadLuan = require "java:luan.modules.ThreadLuan"
+local Luan = require "luan:Luan.luan"
+local error = Luan.error
+local set_metatable = Luan.set_metatable or error()
+
 
 local M = {}
 
 M.fork = ThreadLuan.fork
 M.schedule = ThreadLuan.schedule
 
+
+M.global = {}  -- shared across threads
+local map = ThreadLuan.StringMap.new()
+local global_mt = {}
+set_metatable(M.global,global_mt)
+
+function global_mt.__index(_,key)
+	return map.get(key)
+end
+
+function global_mt.__new_index(_,key,value)
+	map.set(key,value)
+end
+
+function global_mt.get_timeout()
+	return map.timeout
+end
+
+function global_mt.set_timeout(timeout)
+	map.timeout = timeout
+end
+
+
 return M
--- a/src/luan/modules/ThreadLuan.java	Mon Sep 05 15:19:44 2016 -0600
+++ b/src/luan/modules/ThreadLuan.java	Mon Sep 05 16:08:00 2016 -0600
@@ -1,6 +1,8 @@
 package luan.modules;
 
 import java.io.Closeable;
+import java.util.Map;
+import java.util.LinkedHashMap;
 import java.util.concurrent.Executor;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
@@ -68,4 +70,32 @@
 		luan.onClose(c);
 	}
 
+
+	public static class StringMap {
+
+		private static class Value {
+			final long time = System.currentTimeMillis();
+			final String s;
+
+			Value(String s) {
+				this.s = s;
+			}
+		}
+
+		public long timeout = 60000L;  // one minute
+		private Map<String,Value> map = new LinkedHashMap<String,Value>() {
+			protected boolean removeEldestEntry(Map.Entry<String,Value> eldest) {
+				return eldest.getValue().time < System.currentTimeMillis() - timeout;
+			}
+		};
+
+		public synchronized String get(String key) {
+			Value val = map.get(key);
+			return val==null ? null : val.s;
+		}
+
+		public synchronized void set(String key,String s) {
+			map.put(key,new Value(s));
+		}
+	}
 }