OpenComputerScripts/vector.lua

110 lines
2.0 KiB
Lua
Raw Normal View History

2017-10-10 09:47:00 +08:00
require("class")
2017-10-11 22:20:32 +08:00
Vector = class("Vector")
2017-10-10 09:47:00 +08:00
function Vector:_reset()
2017-10-11 22:20:32 +08:00
self.sz = 0
self.bus = {}
2017-10-10 09:47:00 +08:00
end
function Vector:ctor(t)
2017-10-11 22:20:32 +08:00
self:_reset()
if ((t ~= nil) and (type(t) == "table")) then
for k, v in pairs(t) do
local x = {}
x.first = k
x.second = v
self:push_back(x)
end --for
end --if
2017-10-10 09:47:00 +08:00
end --func
function Vector:empty()
2017-10-11 22:20:32 +08:00
return self.sz == 0
2017-10-10 09:47:00 +08:00
end
function Vector:push_back(val)
2017-10-11 22:20:32 +08:00
self.bus[self.sz] = val
self.sz = self.sz + 1
2017-10-10 09:47:00 +08:00
end
function Vector:pop_back()
2017-10-11 22:20:32 +08:00
if (self:empty()) then
return nil
else
local val = self.bus[self.sz - 1]
self.bus[self.sz - 1] = nil
self.sz = self.sz - 1
return val
end
2017-10-10 09:47:00 +08:00
end
function Vector:front()
2017-10-11 22:20:32 +08:00
if (self:empty()) then
return nil
else
return self.bus[0]
end
2017-10-10 09:47:00 +08:00
end
function Vector:back()
2017-10-11 22:20:32 +08:00
if (self:empty()) then
return nil
else
return self.bus[self.sz - 1]
end
2017-10-10 09:47:00 +08:00
end
function Vector:clear()
2017-10-11 22:20:32 +08:00
self:_reset()
2017-10-10 09:47:00 +08:00
end
function Vector:at(index)
2017-10-11 22:20:32 +08:00
if (type(index) ~= "number") then
return nil
elseif (self:empty()) then
return nil
elseif (index < 0) then
return nil
elseif (index >= self.sz) then
return nil
else
return self.bus[index]
end
2017-10-10 09:47:00 +08:00
end
function Vector:size()
2017-10-11 22:20:32 +08:00
return self.sz
2017-10-10 09:47:00 +08:00
end
2017-10-11 22:20:32 +08:00
function Vector:insert_after(index, val)
if (type(index) ~= "number") then
return nil
elseif (index >= self.sz) then
return nil
elseif (index < -1) then
return nil
else
for i = self.sz - 1, index + 1, -1 do
self.bus[i + 1] = self.bus[i]
end
self.bus[index + 1] = val
self.sz = self.sz + 1
end
2017-10-10 09:47:00 +08:00
end
function Vector:erase(index)
2017-10-11 22:20:32 +08:00
if (type(index) ~= "number") then
return nil
elseif (index >= self.sz) then
return nil
elseif (index < 0) then
return nil
else
for i = index + 1, self.sz - 1, 1 do
self.bus[i - 1] = self.bus[i]
end
self.sz = self.sz - 1
end
2017-10-10 09:47:00 +08:00
end