forth-stuff/InputStream.tl

75 lines
1.3 KiB
Plaintext
Raw Normal View History

2021-05-12 03:58:33 +00:00
local type InputStream = record
str: string
offset: number
refill: function(): string
new: function(InputStream): InputStream
new: function(InputStream, function(): string): InputStream
setRefill: function(InputStream, function(): string)
readCurrentCharacter: function(): string
advanceOffset: function(): string
2021-05-12 03:58:33 +00:00
end
local istream_mt = {__index = InputStream}
function InputStream:_manageBuffer()
if not self.str then
self.str = self.refill()
self.offset = 1
end
if self.offset > #self.str + 1 then
2021-05-12 03:58:33 +00:00
self.str = self.refill()
self.offset = 1
end
end
-- constructors
function InputStream:new(): InputStream
return setmetatable(
{
string = "",
offset = 1
} as InputStream,
istream_mt)
end
function InputStream:new(refill: function(): string): InputStream
local mt = setmetatable(
{
string = "",
offset = 1
} as InputStream,
istream_mt)
mt:setRefill(refill)
return mt
end
2021-05-12 03:58:33 +00:00
-- setters/getters
function InputStream:setRefill(func: function(): string)
self.refill = func
end
--
function InputStream:readCurrentCharacter(): string
self:_manageBuffer()
return self.str:sub(self.offset, self.offset)
2021-05-12 03:58:33 +00:00
end
function InputStream:advanceOffset(): string
local current_char = self.str:sub(self.offset, self.offset)
2021-05-12 03:58:33 +00:00
self.offset = self.offset + 1
self:_manageBuffer()
return current_char
2021-05-12 03:58:33 +00:00
end
return InputStream