A couple of io fixes

- Use expect within io.write before calling the handle's write
   function. Closes #338
 - Coerce to string in write before doing any writing. Fixes #339
This commit is contained in:
SquidDev 2020-01-01 09:01:00 +00:00
parent 93a9ebc4f6
commit a48c3d0ba8
4 changed files with 34 additions and 1 deletions

View File

@ -207,6 +207,7 @@ function write( sText )
end
-- Print the line with proper word wrapping
sText = tostring(sText)
while #sText > 0 do
local whitespace = string.match( sText, "^[ \t]+" )
if whitespace then

View File

@ -122,7 +122,11 @@ handleMetatable = {
if not handle.write then return nil, "file is not writable" end
local n = select("#", ...)
for i = 1, n do handle.write(select(i, ...)) end
for i = 1, n do
local arg = select(i, ...)
expect(1, arg, "string", "number")
handle.write(arg)
end
return self
end,
},

View File

@ -1,3 +1,5 @@
local with_window = require "test_helpers".with_window
describe("The Lua base library", function()
describe("sleep", function()
it("validates arguments", function()
@ -13,6 +15,16 @@ describe("The Lua base library", function()
write("")
expect.error(write, nil):eq("bad argument #1 (expected string or number, got nil)")
end)
it("writes numbers", function()
local w = with_window(5, 5, function() write(123) end)
expect(w.getLine(1)):eq("123 ")
end)
it("writes strings", function()
local w = with_window(5, 5, function() write("abc") end)
expect(w.getLine(1)):eq("abc ")
end)
end)
describe("loadfile", function()

View File

@ -41,6 +41,22 @@ local function capture_program(stub, program, ...)
}
end
--- Run a function redirecting to a new window with the given dimensions
--
-- @tparam number width The window's width
-- @tparam number height The window's height
-- @tparam function() fn The action to run
-- @treturn window.Window The window, whose content can be queried.
local function with_window(width, height, fn)
local current = term.current()
local redirect = window.create(current, 1, 1, width, height, false)
term.redirect(redirect)
fn()
term.redirect(current)
return redirect
end
return {
capture_program = capture_program,
with_window = with_window,
}