1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2024-10-02 17:00:47 +00:00

Use cc.strings.wrap inside slowWrite

Means we don't end up re-wrapping text and producing incorrect results.
Fixes #865
This commit is contained in:
Jonathan Coates 2021-08-01 08:43:37 +01:00
parent a1821035d3
commit 686c6a4c44
No known key found for this signature in database
GPG Key ID: B9E431FF07C98D06
3 changed files with 29 additions and 17 deletions

View File

@ -5,35 +5,32 @@
local expect = dofile("rom/modules/main/cc/expect.lua")
local expect, field = expect.expect, expect.field
local wrap = dofile("rom/modules/main/cc/strings.lua").wrap
--- Slowly writes string text at current cursor position,
-- character-by-character.
--
-- Like @{_G.write}, this does not insert a newline at the end.
--
-- @tparam string sText The the text to write to the screen
-- @tparam[opt] number nRate The number of characters to write each second,
-- @tparam string text The the text to write to the screen
-- @tparam[opt] number rate The number of characters to write each second,
-- Defaults to 20.
-- @usage textutils.slowWrite("Hello, world!")
-- @usage textutils.slowWrite("Hello, world!", 5)
function slowWrite(sText, nRate)
expect(2, nRate, "number", "nil")
nRate = nRate or 20
if nRate < 0 then
function slowWrite(text, rate)
expect(2, rate, "number", "nil")
rate = rate or 20
if rate < 0 then
error("Rate must be positive", 2)
end
local nSleep = 1 / nRate
local to_sleep = 1 / rate
sText = tostring(sText)
local x, y = term.getCursorPos()
local len = #sText
local wrapped_lines = wrap(tostring(text), (term.getSize()))
local wrapped_str = table.concat(wrapped_lines, "\n")
for n = 1, len do
term.setCursorPos(x, y)
sleep(nSleep)
local nLines = write(string.sub(sText, 1, n))
local _, newY = term.getCursorPos()
y = newY - nLines
for n = 1, #wrapped_str do
sleep(to_sleep)
write(wrapped_str:sub(n, n))
end
end

View File

@ -3,7 +3,7 @@
-- @module cc.strings
-- @see textutils For additional string related utilities.
local expect = require "cc.expect".expect
local expect = (require and require("cc.expect") or dofile("rom/modules/main/cc/expect.lua")).expect
--[[- Wraps a block of text, so that each line fits within the given width.

View File

@ -1,8 +1,23 @@
local helpers = require "test_helpers"
describe("The textutils library", function()
describe("textutils.slowWrite", function()
it("validates arguments", function()
expect.error(textutils.slowWrite, nil, false):eq("bad argument #2 (expected number, got boolean)")
end)
it("wraps text correctly", function()
local count = 0
stub(_G, "sleep", function() count = count + 1 end)
local w = helpers.with_window(20, 3, function()
textutils.slowWrite("This is a long string which one would hope wraps.")
end)
expect(w.getLine(1)):eq "This is a long "
expect(w.getLine(2)):eq "string which one "
expect(w.getLine(3)):eq "would hope wraps. "
expect(count):eq(51)
end)
end)
describe("textutils.formatTime", function()