Skip to content

Instantly share code, notes, and snippets.

@jabb
Created March 31, 2012 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jabb/2259730 to your computer and use it in GitHub Desktop.
Save jabb/2259730 to your computer and use it in GitHub Desktop.
Manages set of 2D points.
#!/usr/bin/luajit
local point_set_mt = {}
function point_set_mt:has_point(x, y)
return self._points[x .. ',' .. y] ~= nil
end
function point_set_mt:add_point(x, y)
if not self:has_point(x, y) then
self._points[x .. ',' .. y] = true
table.insert(self._points, {x = x, y = y})
end
end
function point_set_mt:remove_point(x, y)
if self:has_point(x, y) then
self._points[x .. ',' .. y] = nil
for i = 1, #self._points do
local point = self._points[i]
if point.x == x and point.y == y then
table.remove(self._points, i)
break
end
end
end
end
function point_set_mt:random_point()
if #self._points > 0 then
local point = self._points[math.random(#self._points)]
return point.x, point.y
end
end
function point_set_mt:iterate()
local i = 1
return function()
if i <= #self._points then
local point = self._points[i]
i = i + 1
return point.x, point.y
end
end
end
function point_set_mt:merge(other)
for x, y in other:iterate() do
self:add_point(x, y)
end
end
local function point_set()
local self = {}
self._points = {}
setmetatable(self, {__index = point_set_mt})
return self
end
return point_set
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment