Created
August 31, 2019 18:59
-
-
Save boatboatboatboat/d405be8d9574638f3029aaa880c8f84d to your computer and use it in GitHub Desktop.
fake static array
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
local Array = {}; | |
local function lerrorf(l, s, ...) | |
error(string.format(s, ...), l + 1); | |
end | |
function Array.new(size) | |
local new = | |
{ | |
size = size; | |
internal = {}; | |
}; | |
local o = {}; | |
function o:destroy() | |
new.internal = nil; | |
new.size = 0; | |
new = nil; | |
end | |
setmetatable( | |
o, | |
{ | |
__index = function(t, k) | |
local n = tonumber(k) or 0 | |
if n >= 1 and n <= new.size then | |
return (new.internal[n]); | |
else | |
lerrorf( | |
2, | |
"index out of range: %d not within 1..%d", | |
n, | |
new.size + 1 | |
); | |
end | |
end, | |
__newindex = function(t, k, v) | |
local n = tonumber(k) or 0; | |
if n >= 1 and n <= new.size then | |
new.internal[n] = v; | |
else | |
lerrorf( | |
2, | |
"index out of range: %d not within 1..%d", | |
n, | |
new.size + 1 | |
); | |
end | |
end | |
} | |
); | |
return (o); | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment