view core/src/luan/modules/Io.luan @ 424:750a68eceb1d

minor
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 01 May 2015 16:33:42 -0600
parents af82b266fe89
children 5b36f663a1b8
line wrap: on
line source

java()
local IoLuan = require "java:luan.modules.IoLuan"
local System = require "java:java.lang.System"

read_console_line = IoLuan.read_console_line
schemes = IoLuan.newSchemes()
Uri = IoLuan.Uri
stdin = IoLuan.defaultStdin.table()
socket_server = IoLuan.socket_server
stdout = IoLuan.textWriter(System.out)
stderr = IoLuan.textWriter(System.err)


local Luan = require "luan:Luan"
local to_string = Luan.to_string
local type = Luan.type
local try = Luan.try
local ipairs = Luan.ipairs
local pairs = Luan.pairs
local Table = require "luan:Table"

function print_to(out,...)
	local list = {}
	for v in Luan.values(...) do
		list[#list+1] = to_string(v)
		list[#list+1] = '\t'
	end
	if #list == 0 then
		out.write( '\n' )
	else
		list[#list] = '\n'
		out.write( Table.unpack(list) )
	end
end

function print(...)
	print_to(stdout,...)
end


-- repr

local function do_repr(obj,done)
	local tp = type(obj)
	if tp == "table" then
		if done[obj] == true then
			%><circular reference><%
			return
		end
		done[obj] = true
		%>{<%
		local is_first = true
		local in_list = {}
		for key, value in ipairs(obj) do
			if is_first then is_first = false else %>, <% end
			do_repr(value,done)
			in_list[key] = true
		end
		for key, value in pairs(obj) do
			if in_list[key] ~= true then
				if is_first then is_first = false else %>, <% end
				if type(key) == "string" and key.match "^[a-zA-Z_][a-zA-Z_0-9]*$" ~= nil then
					%><%=key%><%
				elseif type(key) == "table" then
					%>[<<%=key%>>]<%
				else
					%>[<%do_repr(key,done)%>]<%
				end
				%>=<% do_repr(value,done)
			end
		end
		%>}<%
	elseif tp == "string" then
		%>"<%=obj.encode()%>"<%
	elseif tp == "nil" or tp == "boolean" or tp == "number" then
		%><%=obj%><%
	else
		%><<%=obj%>><%
	end
end

function repr(obj)
	local old_out = stdout
	return try {
		function()
			local string_uri = Uri "string:"
			stdout = string_uri.text_writer()
			do_repr(obj,{})
			stdout.close()
			return string_uri.read_text()
		end;
		finally = function()
			stdout = old_out
		end;
	}
end


-- useful for SimplyHTML responsiveness

NO = {}

function dont_write_when_no(write_fn)
	return function(...)
		for v in Luan.values(...) do
			if v == NO then
				return
			end
		end
		write_fn(...)
	end
end