lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sat, Jul 3, 2021 at 12:44 AM Xmilia Hermit wrote:
How about:

-- compressor.lua
local num_bits = 64

local function Encode(what)
     local tab = {}
     for i = 1, num_bits do
         if what & (1 << (i - 1)) ~= 0 then
             tab[i + 0.5] = true
         end
     end
     for k, v in pairs(tab) do
         tab[k] = nil
     end
     return tab
end

return Encode(...)

-- decompressor.lua
local num_bits = 64

function Decode(tab)
     local num = 0
     for i = 1, num_bits do
         if pcall(next, tab, i + 0.5) then
             num = num | (1 << (i - 1))
         end
     end
     return num
end

return Decode(...)

It is simpler, smaller, uses less memory.

Almost solved!
64 is better than 256, but still not good enough
Try to use the same idea to reduce hash part size to 8 hash slots.

 
And another one using callbacks via __gc metamethod:

-- compressor.lua
local function Encode(what)
     local tab = {}
     local function gc()
         if not tab.pass then
             setmetatable({}, {__gc = gc})
         else
             tab.res = what
         end
     end
     gc()
     return tab
end

return Encode(...)

-- decompressor.lua
local function ForceGC()
     local gc = false
     setmetatable({}, {__gc = function() gc = true end})
     local mem = {}
     while not gc do
         mem = {mem}
     end
end

local function Decode(tab)
     tab.pass = true
     ForceGC()
     return tab.res
end

return Decode(...)

Wonderful idea!