Skip to content

Instantly share code, notes, and snippets.

@wfrsk
Last active March 18, 2023 21:10
Embed
What would you like to do?
multidimensional bitmaps in Lua
--[[
This file is licensed under the license `CC BY-NC-ND 4.0`, visit "https://creativecommons.org/licenses/by-nc-nd/4.0/" for additional information.
author: wfrsk @ github.com
]]
local function make_bitmap( x_bounds )
local integers_required = math.ceil( x_bounds / 64 )
local internal_bitmap, external_adapter do
internal_bitmap = { } do
for index = 1, integers_required do
internal_bitmap[ index ] = 0
end
end
local function index_routine( _, bitspace_index )
assert( type( bitspace_index ) == "number", "index must be an integer" )
local integer_index, bit_index = math.ceil( bitspace_index / 64 ), bitspace_index % 64
return ( assert( internal_bitmap[ integer_index ], "index given out of bounds for bitmap" ) & ( 1 << ( bit_index - 1 ) ) ) == ( 1 << ( bit_index - 1 ) ) and 1 or 0
end
local function newindex_routine( _, bitspace_index, new_value )
assert( type( bitspace_index ) == "number", "index must be an integer" )
local integer_index, bit_index = math.ceil( bitspace_index / 64 ), bitspace_index % 64
internal_bitmap[ integer_index ] = ( new_value & 1 ) == 1 and assert( internal_bitmap[ integer_index ], "index given out of bounds for bitmap" ) | ( 1 << ( bit_index - 1 ) ) or assert( internal_bitmap[ integer_index ], "index given out of bounds for bitmap" ) & ~( 1 << ( bit_index - 1 ) )
end
external_adapter = setmetatable( { }, { __index = index_routine, __newindex = newindex_routine } )
end
return external_adapter
end
local function make_bitmap_2d( x_bounds, y_bounds )
local bidimensional_bitmap = { } do
for index = 1, x_bounds do
bidimensional_bitmap[ index ] = make_bitmap( y_bounds )
end
end
return bidimensional_bitmap
end
local function make_bitmap_3d( x_bounds, y_bounds, z_bounds )
local tridimensional_bitmap = { } do
for index = 1, x_bounds do
tridimensional_bitmap[ index ] = make_bitmap_2d( y_bounds, z_bounds )
end
end
return tridimensional_bitmap
end
return { make_bitmap = make_bitmap, make_bitmap_2d = make_bitmap_2d, make_bitmap_3d = make_bitmap_3d }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment