Created
April 8, 2024 13:28
-
-
Save ohusq/11205c2342577a105cb82b51723ea56a 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
-- 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