From 71642b4884f1e18a60aa17c94b034e20c4db15bb Mon Sep 17 00:00:00 2001 From: Guilian Date: Sat, 18 Jan 2025 18:50:03 +0100 Subject: [PATCH] fix: fix issue with clean_text_nodes modifying arrary while iterating on it --- html.lua | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/html.lua b/html.lua index 87f61d0..18bd07a 100644 --- a/html.lua +++ b/html.lua @@ -3,6 +3,13 @@ local function trim(str) return str:match("^%s*(.-)%s*$") end +local function shallow_copy(t) + local t2 = {} + for k,v in pairs(t) do + t2[k] = v + end + return t2 +end local M = {} @@ -407,7 +414,7 @@ function M.parse_tokens_into_document( TOKENS ) i = i+1 end - DOCUMENT = M.clean_text_nodes( DOCUMENT ) + M.clean_text_nodes( DOCUMENT ) return DOCUMENT end @@ -420,7 +427,7 @@ function M.clean_text_nodes(node) return end - for _, child in ipairs(node.children) do + for _, child in ipairs( shallow_copy(node.children) ) do M.clean_text_nodes( child ) end return @@ -432,7 +439,7 @@ function M.clean_text_nodes(node) error("Text node without a parent; should be impossible !") end - for i, child in ipairs(node.parent.children) do + for i, child in ipairs( shallow_copy(node.parent.children) ) do if child == node then table.remove( node.parent.children, i ) break