Skip to content

Instantly share code, notes, and snippets.

@ohusq
Created April 8, 2024 13:28
Show Gist options
  • Save ohusq/11205c2342577a105cb82b51723ea56a to your computer and use it in GitHub Desktop.
Save ohusq/11205c2342577a105cb82b51723ea56a to your computer and use it in GitHub Desktop.
-- Make vectors like in C++ in Lua! | @ohusq
local Vector = {}
Vector.__index = Vector
function Vector.new(expectedType)
local self = setmetatable({}, Vector)
self.data = {}
self.expectedType = expectedType
return self
end
function Vector:push_back(value)
if type(value) == self.expectedType then
table.insert(self.data, value)
else
error("Invalid data type")
end
end
function Vector:size()
return #self.data
end
function Vector:at(index)
return self.data[index]
end
-- Example usage
local intVector = Vector.new("number")
intVector:push_back(1)
intVector:push_back(2)
-- intVector:push_back("Hello")
local strVector = Vector.new("string")
strVector:push_back("Hello")
strVector:push_back("World")
-- strVector:push_back(123)
print("Int Vector Size:", intVector:size())
print("String Vector Size:", strVector:size())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment