Skip to content

Instantly share code, notes, and snippets.

@cwchentw
Last active April 16, 2024 01:49
Show Gist options
  • Save cwchentw/6bc5ef6cb448cb5935c4c89adaca0b4f to your computer and use it in GitHub Desktop.
Save cwchentw/6bc5ef6cb448cb5935c4c89adaca0b4f to your computer and use it in GitHub Desktop.
Array-based List in Pure Lua (Apache 2.0)
local List = {}
package.loaded["List"] = List
List.__index = List
function List:new()
self = {}
self._arr = {}
setmetatable(self, List)
return self
end
function List:len()
return #(self._arr)
end
function List:at(i)
return self._arr[i]
end
function List:push(data)
table.insert(self._arr, data)
end
function List:pop()
if self:len() <= 0 then
return nil
end
return table.remove(self._arr)
end
function List:shift(data)
table.insert(self._arr, 1, data)
end
function List:unshift()
if self:len() <= 0 then
return nil
end
return table.remove(self._arr, 1)
end
function List:insert(index, data)
table.insert(self._arr, index, data)
end
function List:remove(index)
if self:len() <= 0 then
return nil
end
return table.remove(self._arr, index)
end
return List
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment