forth-stuff/InputStream.tl

83 lines
1.5 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, 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
2021-05-19 05:37:47 +00:00
if self.offset > #self.str then
2021-05-12 03:58:33 +00:00
self.str = self.refill()
self.offset = 1
end
end
2021-05-19 05:37:47 +00:00
local function initial_stream(): string
return "DUMMY"
end
2021-05-12 03:58:33 +00:00
-- constructors
function InputStream:new(): InputStream
2021-05-19 05:37:47 +00:00
local mt = setmetatable(
2021-05-12 03:58:33 +00:00
{
string = "",
2021-05-19 05:37:47 +00:00
offset = 1,
refill = initial_stream
2021-05-12 03:58:33 +00:00
} as InputStream,
istream_mt)
2021-05-19 05:37:47 +00:00
mt:setRefill(initial_stream)
return mt
2021-05-12 03:58:33 +00:00
end
function InputStream:new(refill: function(): string): InputStream
2021-05-19 05:37:47 +00:00
refill = refill or initial_stream
local mt = setmetatable(
{
string = "",
2021-05-19 05:37:47 +00:00
offset = 1,
refill = function(): string return "DUMMY" end
} 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
2021-05-19 05:37:47 +00:00
self:_manageBuffer()
2021-05-12 03:58:33 +00:00
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
2021-05-19 05:37:47 +00:00
self:_manageBuffer()
local current_char = self.str:sub(self.offset, self.offset)
2021-05-12 03:58:33 +00:00
self.offset = self.offset + 1
return current_char
2021-05-12 03:58:33 +00:00
end
return InputStream