Mercurial Hosting > luan
comparison core/src/luan/modules/Io.luan @ 422:af82b266fe89
add Io.repr()
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Fri, 01 May 2015 16:13:52 -0600 |
parents | 62b457c50594 |
children | 750a68eceb1d |
comparison
equal
deleted
inserted
replaced
421:b31d614343e8 | 422:af82b266fe89 |
---|---|
11 stderr = IoLuan.textWriter(System.err) | 11 stderr = IoLuan.textWriter(System.err) |
12 | 12 |
13 | 13 |
14 local Luan = require "luan:Luan" | 14 local Luan = require "luan:Luan" |
15 local to_string = Luan.to_string | 15 local to_string = Luan.to_string |
16 local type = Luan.type | |
17 local try = Luan.try | |
18 local ipairs = Luan.ipairs | |
19 local pairs = Luan.pairs | |
16 local Table = require "luan:Table" | 20 local Table = require "luan:Table" |
17 | 21 |
18 function print_to(out,...) | 22 function print_to(out,...) |
19 local list = {} | 23 local list = {} |
20 for v in Luan.values(...) do | 24 for v in Luan.values(...) do |
32 function print(...) | 36 function print(...) |
33 print_to(stdout,...) | 37 print_to(stdout,...) |
34 end | 38 end |
35 | 39 |
36 | 40 |
41 -- repr | |
42 | |
43 local function do_repr(obj,done) | |
44 local tp = type(obj) | |
45 if tp == "table" then | |
46 if done[obj] == true then | |
47 %><circular reference><% | |
48 return | |
49 end | |
50 done[obj] = true | |
51 %>{<% | |
52 local is_first = true | |
53 local in_list = {} | |
54 for key, value in ipairs(obj) do | |
55 if is_first then is_first = false else %>, <% end | |
56 do_repr(value,done) | |
57 in_list[key] = true | |
58 end | |
59 for key, value in pairs(obj) do | |
60 if in_list[key] ~= true then | |
61 if is_first then is_first = false else %>, <% end | |
62 if type(key) == "string" and key.match "^[a-zA-Z_][a-zA-Z_0-9]*$" ~= nil then | |
63 %><%=key%><% | |
64 else | |
65 %>[<%do_repr(key,done)%>]<% | |
66 end | |
67 %>=<% do_repr(value,done) | |
68 end | |
69 end | |
70 %>}<% | |
71 elseif tp == "string" then | |
72 %>"<%=obj.encode()%>"<% | |
73 elseif tp == "nil" or tp == "boolean" or tp == "number" then | |
74 %><%=obj%><% | |
75 else | |
76 %><<%=obj%>><% | |
77 end | |
78 end | |
79 | |
80 function repr(obj) | |
81 local old_out = stdout | |
82 return try { | |
83 function() | |
84 local string_uri = Uri "string:" | |
85 stdout = string_uri.text_writer() | |
86 do_repr(obj,{}) | |
87 stdout.close() | |
88 return string_uri.read_text() | |
89 end; | |
90 finally = function() | |
91 stdout = old_out | |
92 end; | |
93 } | |
94 end | |
95 | |
96 | |
37 -- useful for SimplyHTML responsiveness | 97 -- useful for SimplyHTML responsiveness |
38 | 98 |
39 NO = {} | 99 NO = {} |
40 | 100 |
41 function dont_write_when_no(write_fn) | 101 function dont_write_when_no(write_fn) |