Compatible with Lua 5.3
Last active
May 20, 2020 13:36
-
-
Save daurnimator/aa23173220a5b3d1a97a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local S = require "sequence".new | |
local a = S(1,2,nil,4); | |
a:remove(3); | |
for i,v in ipairs(a) do print(i,v) end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local sequence_methods = {} | |
local sequence_mt = { | |
__name = "sequence"; | |
__index = sequence_methods; | |
__len = function(t) return t.n end; | |
} | |
local function new(...) | |
return setmetatable(table.pack(...), sequence_mt) | |
end | |
sequence_methods.concat = table.concat | |
sequence_methods.unpack = table.unpack | |
sequence_methods.sort = table.sort | |
-- Functions that mutate | |
function sequence_methods:insert(...) | |
table.insert(self, ...) | |
self.n = self.n + 1 | |
end | |
function sequence_methods:remove(pos) | |
if pos == nil then | |
pos = self.n | |
elseif pos > self.n + 1 then | |
error("bad argument #1 to 'remove' (position out of bounds)") | |
end | |
local v = table.remove(self, pos) | |
if self.n > 0 then | |
self.n = self.n - 1 | |
end | |
return v | |
end | |
function sequence_methods:move(f, e, t, dest) | |
dest = dest or self | |
table.move(self, f, e, t, dest) | |
if getmetatable(dest) == sequence_mt then | |
local dest_last = e-f+t | |
if dest_last > dest.n then | |
dest.n = dest_last | |
end | |
end | |
end | |
-- __ipairs was deprecated in 5.3, support may be compiled out. | |
local function inext(self, last) | |
if last >= #self then return end | |
local i = last+1 | |
return i, self[i] | |
end | |
function sequence_mt:__ipairs() | |
return inext, self, 0 | |
end | |
return { | |
new = new; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment