Created
January 23, 2025 01:50
-
-
Save marcs-feh/766f86e3532ae4cf99e12c26c04aba9b to your computer and use it in GitHub Desktop.
lua array
This file contains hidden or 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 Array = { | |
__tostring = function(self) | |
if #self == 0 then | |
return '[]' | |
end | |
local s = '[' | |
for _, v in ipairs(self) do | |
s = s .. tostring(v) .. ', ' | |
end | |
return s:sub(1, #s - 2) .. ']' | |
end, | |
} | |
function Array:concat(b) | |
local res = Array:new() | |
for _, v in ipairs(self) do | |
res[#res+1] = v | |
end | |
for _, v in ipairs(b) do | |
res[#res+1] = v | |
end | |
return res | |
end | |
function Array:rep(count) | |
local res = Array:new() | |
for _ = 1, count, 1 do | |
for _, v in ipairs(self) do | |
res[#res+1] = v | |
end | |
end | |
return res | |
end | |
function Array:new(obj) | |
obj = obj or {} | |
assert(type(obj) == 'table', 'Initializer object must be a table') | |
setmetatable(obj, self) | |
self.__index = self | |
return obj | |
end | |
function Array:append(...) | |
local args = table.pack(...) | |
for _, v in ipairs(args) do | |
self[#self+1] = v | |
end | |
end | |
function Array:pop() | |
local v = self[#self] | |
self[#self] = nil | |
return v | |
end | |
function Array:insert(idx, v) | |
table.insert(self, idx, v) | |
end | |
function Array:remove(idx) | |
table.remove(self, idx) | |
end | |
Array.__add = Array.concat | |
return Array | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment