Helpful scripts
Posted: Fri Jul 03, 2015 6:18 pm
Sometimes a script is too simple for you to turn into a library, or maybe they are depended on another library's features. But that doesn't mean we should keep them for ourselves. What are some scripts that have really helped you and is since then in almost all your projects?
I'll start with a few examples:
Asset (uses Classic, like most of my scripts)
Allows me to do this:
And for input (uses Classic and Lume):
Which allows me to do this:
I'll start with a few examples:
Asset (uses Classic, like most of my scripts)
Code: Select all
local Asset = Object:extend()
local function stripString(base, s)
local a = s:sub(base:len()+2,s:len())
return a:sub(0, a:find("%.")-1)
end
local function loadFiles(base, dir, files)
dir = dir or base
local items = love.filesystem.getDirectoryItems(dir)
for i,v in ipairs(items) do
local file = dir .. "/" .. v
if love.filesystem.isFile(dir .. "/" .. v) then
files[
stripString(base, file)
] = file
else
loadFiles(base, dir .. "/" .. v, files)
end
end
return files
end
function Asset:new()
self.imgCache = {}
self.imgDirs = loadFiles("images", nil,{})
end
function Asset:image(url, force)
if not self.imgDirs[url] then error('The image "' .. url .. '" does not exist!') end
local img
if force or not self.imgCache[url] then
img = love.graphics.newImage(self.imgDirs[url])
self.imgCache[url] = img
else
img = self.imgCache[url]
end
return img
end
function Asset:__tostring()
return "Asset"
end
return Asset
Code: Select all
img = Asset:image("nameOfImage")
-- Instead of...
img = love.graphics.newImage("images/nameOfImage.png")
Code: Select all
local Input = Object:extend()
function Input:new()
self._pressed = {}
self._released = {}
self._custom = {}
end
function Input:reset()
self._pressed = {}
self._released = {}
end
function Input:isPressed(...)
return lume.any({...}, function (a) return self._custom[a] and lume.any(self._custom[a], function (b) return lume.find(self._pressed, b) end) end)
end
function Input:isReleased(...)
return lume.any({...}, function (a) return self._custom[a] and lume.any(self._custom[a], function (b) return lume.find(self._released, b) end) end)
end
function Input:isDown(...)
return lume.any({...}, function (a) return self._custom[a] and lume.any(self._custom[a], function (b) return love.keyboard.isDown(b) end) end)
end
function Input:set(name, t)
self._custom[name] = t
end
function Input:inputpressed(input)
table.insert(self._pressed, input)
if not self._custom[input] then
self._custom[input] = {input}
end
end
function Input:inputreleased(input)
table.insert(self._released, input)
end
function Input:__tostring()
return "Input | pressed: " .. (unpack(self._pressed) or " ") .. ", released: " .. (unpack(self._released) or " ")
end
return Input
Code: Select all
Input:set("jump",{"space","up","w"})
Input:isPressed("jump")