Skip to content

Instantly share code, notes, and snippets.

@jabb
Created March 31, 2012 05:37
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/2259719 to your computer and use it in GitHub Desktop.
Save jabb/2259719 to your computer and use it in GitHub Desktop.
Simple 2D layer for games.
#!/usr/bin/luajit
local ffi = require 'ffi'
local layer_mt = {}
function layer_mt:top_left(x, y)
self._x1, self._y1 = x - 1, y - 1
end
function layer_mt:index(x, y)
x, y = x + self._x1, y + self._y1
if x < 1 or y < 1 or x > self._width or y > self._height then
return 0
else
return 1 + (x - 1) + (y - 1) * self._width
end
end
function layer_mt:get(x, y)
return self._cells[self:index(x, y)]
end
function layer_mt:set(x, y, v)
x, y = x + self._x1, y + self._y1
if x < 1 or y < 1 or x > self._width or y > self._height then
return
end
self._cells[1 + (x - 1) + (y - 1) * self._width] = v
end
function layer_mt:get_width()
return self._width
end
function layer_mt:get_height()
return self._height
end
function layer_mt:fill(v)
for i = 0, self._width * self._height do
self._cells[i] = v
end
end
function layer_mt:set_default(v)
self._cells[0] = v
end
local function layer(ctype, width, height)
local self = {}
self._ctype = ctype
self._width = width
self._height = height
self._x1, self._y1 = 0, 0
self._cells = ffi.new(ctype .. '[?]', 1 + width * height)
setmetatable(self, {__index = layer_mt})
return self
end
return layer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment