Move an object to left, right, up, down on button click using Lua

In some instances we need to move our object to various direction as per the rule in game app. So here is some basic code to move an object to right, left, up and down.

Code Block :

--Make a box
local box = display.newRect(200, 250, 100, 100)
 
--Set the color of the box
box:setFillColor(204, 243, 255)
 
--Library responsible to make buttons
local widget = require "widget"
 
local onPressEvent_btnLeft = function (event )
 
--Remove the event if it added earlier
 Runtime:removeEventListener("enterFrame", moveBox)
    print("Left Button Pressed")
 
   -- Function to move left
    function  moveBox ()
             box.x = box.x - 2;
    end
            Runtime:addEventListener("enterFrame",  moveBox )
end
 
--Left button
local lftBtn= widget.newButton{
    id = "btnLeft",
    left = 0,
    top = 650,
    fontSize = 24,
    label = "Left Button",
    width = 150, height = 100,
    cornerRadius = 8,
    onPress = onPressEvent_btnLeft      -- Press event to change the position of the box
}
 
local onPressEvent_btnRight = function (event )
    Runtime:removeEventListener("enterFrame",  moveBox )
 
   -- Function to move right
     function  moveBox ()
             box.x = box.x + 2;
    end
            Runtime:addEventListener("enterFrame",  moveBox )
end
 
--Define the right button
local rightBtn = widget.newButton{
    id = "btnRight",
    left = 300,
    top = 650,
    label = "Right Button",
    fontSize = 24,
    width = 150, height = 100,
    cornerRadius = 8,    
    onPress = onPressEvent_btnRight
}
 
local onPressEvent_btnTop = function (event )
    Runtime:removeEventListener("enterFrame",  moveBox )
 
     -- Function to move top
     function  moveBox ()
             box.y = box.y - 2;
    end
            Runtime:addEventListener("enterFrame",  moveBox )
end
 
--Top button
local topBtn = widget.newButton{
    id = "btnTop",
    left = 150,
    top = 550,
    label = "Top Button",
    fontSize = 24,
    width = 150, height = 100,
    cornerRadius = 8,    
    onPress = onPressEvent_btnTop
}
 
local onPressEvent_btnDown = function (event )
    Runtime:removeEventListener("enterFrame",  moveBox )
 
     -- Function to move down
     function  moveBox ()
             box.y = box.y + 2;
    end
            Runtime:addEventListener("enterFrame",  moveBox )
end
 
local downBtn = widget.newButton{
    id = "btnDown",
    left = 150,
    top = 750,
    label = "Down Button",
    fontSize = 24,
    width = 150, height = 100,
    cornerRadius = 8,    
    onPress = onPressEvent_btnDown
}
150 150 Burnignorance | Where Minds Meet And Sparks Fly!