Skip to content

Instantly share code, notes, and snippets.

@LeonLenclos
Last active January 31, 2021 01:11
Show Gist options
  • Save LeonLenclos/b09dbb1ae7fbc3d8a2013b071466122a to your computer and use it in GitHub Desktop.
Save LeonLenclos/b09dbb1ae7fbc3d8a2013b071466122a to your computer and use it in GitHub Desktop.
Lua/Love utils
local utils = {}
-- My utils functions for developing games with Love2d
-- Numbers
function utils.mapvalue(val, min, max, mapmin, mapmax)
return ((val-min)/(max-min))*(mapmax-mapmin)+mapmin
end
function utils.constrain(val, min, max)
return val<min and min or val>max and max or val
end
function utils.lerp(start, stop, amount)
return amount * (stop-start) + start
end
function utils.round(val, decimal)
-- TODO: may not work with negative numbers and the decimal opition.
if (decimal) then
return math.floor( (val * 10^decimal) + 0.5) / (10^decimal)
else
return x>=0 and math.floor(x+0.5) or math.ceil(x-0.5)
end
end
function utils.min(a, b)
return a > b and b or a
end
function utils.max(a, b)
return a < b and b or a
end
-- Coords
function utils.indexToCoord(i, w)
return i%w, math.floor(i/w)
end
function utils.coordToIndex(x, y, w)
return x + y * w
end
-- Tables
function utils.reduce(table, fun, acc)
acc = acc==nil and 0 or acc
for k, v in ipairs(table) do
acc = fun(acc, v)
end
return acc
end
function utils.find(table, callback)
for i,v in ipairs(table) do
if callback(v, i, table) then return v end
end
end
function utils.tableRepr(table, depthLimit, indentation)
depthLimit = depthLimit or 2
indentation = indentation or 0
local function tabline (txt)
local tabs = ''
for i=1,indentation do tabs = ' ' .. tabs end
return tabs .. txt .. '\n'
end
txt = tabline('{')
for k,v in pairs(table) do
if type(v) == 'table' then
if depthLimit and indentation > depthLimit then
txt = txt .. tabline(k..': {...}')
else
txt = txt .. tabline(k..': '..utils.tableRepr(v, depthLimit, indentation+1))
end
else
txt = txt .. tabline(k..':'..tostring(v))
end
end
txt = txt .. tabline('}')
return txt
end
-- Love specific
function utils.anyIsDown(controlsList)
return utils.reduce(controlsList, function(a, v) return a or love.keyboard.isDown(v) end, false)
end
return utils
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment