Created
July 1, 2018 04:47
-
-
Save SibGent/e73043f7c180e2b8006ef82d7a6c21c8 to your computer and use it in GitHub Desktop.
Corona SDK - on back tap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module("BackEvent", package.seeall) | |
local composer = require "composer" | |
local event = {} | |
local stack = {} | |
local platform = system.getInfo("platform") | |
local init | |
, executeEvent | |
, openPrevScene | |
, requestExit | |
, onKeyEvent | |
function BackEvent.back() | |
if composer.getSceneName("overlay") then | |
composer.hideOverlay("fade", 400) | |
else | |
if #stack > 1 then | |
openPrevScene() | |
else | |
native.showAlert( "Hey Listen!", "Do you really want to exit?", { "Yes", "No" }, requestExit ) | |
end | |
end | |
end | |
function BackEvent.add(listener) | |
if not table.isValueExists(event, listener) then | |
table.insert(event, listener) | |
end | |
end | |
function BackEvent.remove(listener) | |
local key = table.getKeyByValue(event, listener) | |
if key then | |
table.remove(event, key) | |
end | |
end | |
function init() | |
for name, super in pairs(composer) do | |
if name == "gotoScene" then | |
composer[name] = function(...) | |
super(...) | |
table.insert(stack, {...}) | |
end | |
end | |
if name == "removeScene" then | |
composer[name] = function(...) | |
super(...) | |
local sceneName = ... | |
local stack_id | |
for i = 1, #stack do | |
if table.isValueExists(stack[i], sceneName) then | |
stack_id = i | |
break | |
end | |
end | |
if stack_id then | |
table.remove(stack, stack_id) | |
end | |
end | |
end | |
end | |
if platform == "android" then | |
Runtime:addEventListener("key", onKeyEvent) | |
end | |
end | |
function executeEvent() | |
local isExecuted = true | |
for i = 1, #event do | |
if not event[i]() then | |
isExecuted = false | |
end | |
end | |
return isExecuted | |
end | |
function openPrevScene() | |
table.remove(stack, #stack) | |
local sceneName = stack[#stack][1] | |
local options = stack[#stack][2] | |
composer.gotoScene(sceneName, options) | |
end | |
function requestExit(event) | |
if event.action == "clicked" then | |
if event.index == 1 then | |
native.requestExit() | |
elseif event.index == 2 then | |
end | |
end | |
end | |
function onKeyEvent(event) | |
if platform == "android" then | |
if event.keyName == "back" then | |
if event.phase == "down" then | |
if executeEvent() then | |
BackEvent.back() | |
end | |
end | |
end | |
return true | |
end | |
return false | |
end | |
init() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment