Skip to content

Instantly share code, notes, and snippets.

@pablomayobre
Created January 9, 2015 21:49
Show Gist options
  • Save pablomayobre/7b8765aa2e5f613d328a to your computer and use it in GitHub Desktop.
Save pablomayobre/7b8765aa2e5f613d328a to your computer and use it in GitHub Desktop.
Trigger functions after a predefined sequence of keys have been pressed (LÖVE)
------Copyright 2015 Pablo A. Mayobre------
--Licensed under the terms of MIT Lincense--
local seq = {}
local split = function (text,pat)
local t = {}
while true do
local pos1, pos2 = text:find(pat, 1, true)
if not pos1 then
t[#t + 1] = text
return t
end
t[#t + 1] = text:sub(1, pos1 - 1)
text = text:sub(pos2 + 1)
end
end
local unpack = unpack or table.unpack
seq.new = function (self,f,t)
local steps = {}
for k,v in ipairs(split(t, ",")) do
steps[k] = split(v,"+")
end
self.inst[#self.inst + 1] = {
f = f;
steps = steps;
current = 1;
}
end
seq.update = function (self)
for k,v in ipairs(self.inst) do
if love.keyboard.isDown(unpack(v.steps[v.current])) then
v.current = v.current + 1
end
if v.current > #v.steps then
v.f()
self.inst[k] = nil
end
end
end
return seq
@pablomayobre
Copy link
Author

Define a new sequence using sequences:new() as follows:

sequences = require "sequences"

local callback = function ()
    --This is gonna be called when the sequence is matched
end

local sequence = "up,up,down,down,left,right,left,right,b,a" --The Konami code sequence

sequences:new(callback,sequence)

You can also define key combinations that should be pressed at the same time as follows:

local sequence = "ctrl+shift+c" --Code used for console in games like The Sims and such
sequences:new(calback,sequence)

Or a combination of both things

sequence = "up+down,left+right"
sequences:new(callback,sequence)

Remember to call sequences:update() in you love.update callback

love.update = function ()
    sequences:update()
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment