From d72815720435e586411293220c1c422d065310cb Mon Sep 17 00:00:00 2001 From: Lars Mueller Date: Thu, 4 Mar 2021 08:30:19 +0100 Subject: [PATCH] Add table.rope with :write and :to_text --- table.lua | 13 +++++++++++++ test.lua | 5 +++++ 2 files changed, 18 insertions(+) diff --git a/table.lua b/table.lua index fb07aef..26ee32a 100644 --- a/table.lua +++ b/table.lua @@ -33,6 +33,19 @@ function shuffle(table) return table end +local rope_metatable = {__index = { + write = function(self, text) + table.insert(self, text) + end, + to_text = function(self) + return table.concat(self) + end +}} +--> rope with simple metatable (:write(text) and :to_text()) +function rope(table) + return setmetatable(table or {}, rope_metatable) +end + function is_circular(table) assert(type(table) == "table") local known = {} diff --git a/test.lua b/test.lua index b08e501..01aac94 100644 --- a/test.lua +++ b/test.lua @@ -27,6 +27,11 @@ do assert(nilget({a = {}}, "a", "b", "c") == nil) assert(nilget(nil, "a", "b", "c") == nil) assert(nilget(nil, "a", nil, "c") == nil) + local rope = modlib.table.rope{} + rope:write"hello" + rope:write" " + rope:write"world" + assert(rope:to_text() == "hello world", rope:to_text()) end -- heap