Skip to content

Instantly share code, notes, and snippets.

@silentbicycle
Created May 12, 2013 16:11
Show Gist options
  • Save silentbicycle/5564042 to your computer and use it in GitHub Desktop.
Save silentbicycle/5564042 to your computer and use it in GitHub Desktop.
quick draft of an array/vector library for lua (mostly as an example of metatables)
local NONE = setmetatable({}, {['__tostring'] = function() return "NONE" end})
local Array = {
['__newindex'] = function(a, k, v)
if type(k) ~= "number" then error("bad index") end
if k < 1 then error("out of bounds") end
if a._lim ~= NONE and k <= a._lim then
a._v[k] = v
elseif a._lim == NONE then
if k > a._len then
for i=a._len+1,2*a._len do
a._v[i] = NONE
end
a._len = 2*a._len
end
a._v[k] = v
else
error("out of bounds")
end
end,
['__index'] = function(a, k)
return a._v[k] or NONE
end,
}
-- Make a new array. If an explicit limit is given, the length
-- will be capped, otherwise the array will be doubled on demand
-- and filled with NONEs.
function new(len)
local a = {}
local v = {}
if len then -- const length
len = tonumber(len)
if not len then error("bad length") end
for i=1,len do v[i] = NONE end
a._len = len
a._lim = len
else -- grow on demand
a._len = 1
v[1] = NONE
a._lim = nil
end
a._v=v
return setmetatable(a, Array)
end
function test()
local a = new(3)
for i=1,3 do print(i, a[i]) end
a[2] = 23
print ""
for i=1,3 do print(i, a[i]) end
print ""
local a2 = new()
a2[3] = "badger"
for i=1,5 do print(i, a2[i]) end
a2[9] = "mushroom"
for i=1,10 do print(i, a2[i]) end
end
return { new=new, test=test, NONE=NONE, }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment