why does the Director class make my global variables not visible to external modules in corona? - global-variables

I'm doing basic stuff to understand using external classes/modules with global variables, and now I'm trying to add director. But when I added the director class, my global variables such as applyThrust then became not visible in the external class.
It worked fine before refactoring for Director. Before using director, I only had 2 files, rocket.lua and the mainScreen.lua file below was simply main.lua. I used the same globals, applyThrust and thrustForceY, and it worked.
By the way, the director functionality of switching screens appears to work fine, other than this odd side effect of making the global variables not visible.
I asked this on the corona director forums and got no response so I thought I'd try reliable STO.
Here's the files I'm using with the director stuff :
main.lua
display.setStatusBar (display.HiddenStatusBar)
local director = require ("director")
local mainGroup = display.newGroup()
local function main()
mainGroup:insert(director.directorView)
director:changeScene("menu")
return true
end
main()
menu.lua
module(..., package.seeall)
function new()
local localGroup = display.newGroup()
------------------------------------------------------------------------------
local playText = display.newText("Play",160, 100, "Arial", 32)
playText:setTextColor(0, 0, 255)
localGroup:insert(playText)
local function pressPlay (event)
if event.phase == "ended" then
director:changeScene ("mainScreen")
end
end
playText:addEventListener ("touch", pressPlay)
------------------------------------------------------------------------------
return localGroup
end
mainScreen.lua
local Rocket = require( "rocket" )
local physics = require( "physics" )
module(..., package.seeall)
function new()
local localGroup = display.newGroup()
------------------------------------------------------------------
score = 100
physics.start()
local ground = display.newRect( 60, 170, 60, 60 )
physics.addBody( ground, "static", { density=3.0, friction=0.5, bounce=0.2 } )
rocket = Rocket.new(80, 110)
local upText = display.newText("Up",160, 300, "Arial", 32)
upText:setTextColor(0, 0, 255)
------------- my global variables -----------
thrustForceY = -100
applyThrust = false
local function pressUp (event)
local t = event.target
local phase = event.phase
if( "began" == phase ) then
display.getCurrentStage():setFocus( t )
t.isFocus = true
if( not applyThrust ) then
rocket:addThrust()
end
rocket:applyForce(0, thrustForceY, rocket.x, rocket.y)
applyThrust = true
elseif "ended" == phase or "cancelled" == phase then
rocket:removeThrust()
display.getCurrentStage():setFocus( nil )
t.isFocus = false
applyThrust = false
end
return true
end
upText:addEventListener ("touch", pressUp)
----------------------------------------------
return localGroup
end
rocket.lua
module(..., package.seeall)
local physics = require( "physics" )
--constructor--------------------
function new(x, y)
rocket = display.newGroup()
local body = display.newRect( x, y, 25, 60 )
physics.addBody( body, { density=1.5, friction=0.5, bounce=0.2 } )
body.isFixedRotation = true
rocket:insert(body)
local thrust = {}
function rocket:addThrust()
thrust = display.newRect( body.x, body.y + (body.height / 2) , 10, 10 )
thrust.y = body.y + (body.height / 2) + (thrust.height / 2)
physics.addBody( thrust, { density=1.5, friction=0.5, bounce=0.2 } )
rocket:insert(thrust)
end
function rocket:removeThrust()
rocket:remove(thrust)
end
function rocket:applyForce( xForce, yForce, atPointX, atPointY )
body:applyForce( xForce, yForce, atPointX, atPointY )
end
----------------------------------------------------------------------
-- enterFrame listener for rocket
----------------------------------------------------------------------
function rocket:enterFrame (event)
if( applyThrust ) then
body:applyForce(0, thrustForceY, body.x, body.y)
thrust.y = body.y + (body.height / 2) + (thrust.height / 2)
thrust.x = body.x
else
print("applyThrust is nil")
end
end
Runtime:addEventListener("enterFrame", rocket)
return rocket
end

A global variable in Corona is as simple as using "_G." before your variable.
For example:
lives = 3
Would become:
_G.lives = 3
But Director already has functionality to pass parameters to another scene.... there is no need to use globals.
scene1.lua
local params = {
param1= "http://github.com/",
param2 = "bla-bla"
}
director:changeScene( params, "screen2", "moveFromRight" )
screen2.lua
new = function ( params )
local url = params.param1
local bla = params.param2
...
end

Good point.
Also, you can put all your variables in a file you created and access it from any module.

Related

Bosun: Lookup is giving integer when string is expected

I'm tweaking my bosun.conf to allow my os.cpu.high alert to use a lookup when determining which duration to to use depending on the host:
lookup high_cpu {
entry host=* {
time = 5m
}
entry host=*graylog* {
time = 1h
}
}
alert os.cpu.high {
template = generic.graph
macro = host.based.contacts
$notes = Find CPU usage that is continually high
$duration = lookup("high_cpu", "time")
$host = *
$metric = "sum:rate{counter,,1}:os.cpu{host=$host}"
$q_cpu = q($metric, "$duration", "")
$q = avg($q_cpu)
warn = $q > 95
crit = $q > 99
ignoreUnknown = true
$q_format = %f
$unit_string = %
$generic_graph = $q_cpu
$graph_unit = %
}
This is the error I get when testing:
conf: Test Config:424:4: at <warn = $q > 95>: expr: unexpected "high" in func
I am not very familiar with bosun and this is probably an easy fix, but I'm at my wit's end. Any help would be appreciated
You can't do this, as lookups don't support a string return type.
This particular scenario would be problematic anyways since what you are trying to do is query different amount of times based on the result of the query, so you have a chicken and egg problem.
What you can do is query the max amount of time you want to query and then shorten some results in the set using the crop function. However the crop function is not in a release yet so you would have to get it in master. You can see the documentation with an example of what you are trying to do in this commit for now, i.e.:
lookup test {
entry host=ny-bosun01 {
start = 30
}
entry host=* {
start = 60
}
}
alert test {
template = test
$q = q("avg:rate:os.cpu{host=ny-bosun*}", "5m", "")
$c = crop($q, lookup("test", "start") , 0)
crit = avg($c)
}

Corona sdk composer wont got back to previous scene

I have used coronaSDK composer to have scenes in my application. i have a options button that is able to get to the options scene. however when i put a button on the option scene to go back to mainMenu scene it doesnt work
mainMenu.lua
local composer = require( "composer" )
local scene = composer.newScene()
-- "scene:create()"
function scene:create( event )
local sceneGroup = self.view
local backgroundimg = display.newImage("image/mainBackground.png")
backgroundimg.x = display.contentWidth*0.5
backgroundimg.y = display.contentHeight*0.5
sceneGroup:insert( backgroundimg )
local function startListener( event )
composer.gotoScene( "scene.play" )
end
local start = display.newRect(65,99.5,161,161)
start.alpha = 0.01
start:addEventListener( "tap", startListener )
local function leaderListener( event )
composer.gotoScene( "scene.leaderboards" )
end
local leader = display.newRect(208,227.5,147,147)
leader.alpha = 0.01
leader:addEventListener( "tap", leaderListener )
local function optionsListener( event )
composer.gotoScene( "scene.options" )
end
local options = display.newRect(332,92.5,147,147)
options.alpha = 0.01
options:addEventListener( "tap", optionsListener )
local function quitListener( event )
os.exit()
end
local quit = display.newRect(432,240.5,120,120)
quit.alpha = 0.01
quit:addEventListener( "tap", quitListener )
end
-- "scene:show()"
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
elseif ( phase == "did" ) then
end
end
-- "scene:hide()"
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if ( phase == "will" ) then
elseif ( phase == "did" ) then
end
end
-- "scene:destroy()"
function scene:destroy( event )
local sceneGroup = self.view
end
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
return scene
options.lua
local composer = require( "composer" )
local scene = composer.newScene()
-- "scene:create()"
function scene:create( event )
local sceneGroup = self.view
local function startListener( event )
composer.gotoScene( "scene.mainMenu" )
end
local start = display.newRect(65,99.5,161,161)
start.alpha = 1
start:addEventListener( "tap", startListener )
end
Try using:
composer.gotoScene( "mainMenu" )
Also, you are not adding the objects to the scene group. So, when the scene changes, the objects will not be removed automatically.

Corona Button not passing focus to scrollView

I am having an issue with scrolling when buttons are on the scrollView. The problem is the issue of events not being handled properly. All attempts to pass focus to the scrollView have proven fruitless. An observation I have made is that in this following code, it is not printing back to me, this is even after I was scrolling correctly without the buttons in the way of it.
local function scrollListener( event )
local phase = event.phase
if ( phase == "began" ) then print( "Scroll view was touched" )
elseif ( phase == "moved" ) then print( "Scroll view was moved" )
elseif ( phase == "ended" ) then print( "Scroll view was released" )
end
-- In the event a scroll limit is reached...
if ( event.limitReached ) then
if ( event.direction == "up" ) then print( "Reached top limit" )
elseif ( event.direction == "down" ) then print( "Reached bottom limit" )
elseif ( event.direction == "left" ) then print( "Reached left limit" )
elseif ( event.direction == "right" ) then print( "Reached right limit" )
end
end
return true
end
Here is the actual code being used for the scene:
function scene:enterScene(event)
--local yell=audio.play(ahhh, {channel=1, loops=0, fadein=0})
--Creating the Background
local background=display.newImageRect("background.png", 320, 580)
background.x=160
background.y=240
--Creating the scroll view
local scrollView = widget.newScrollView
{
top = 10,
left = 10,
width = 300,
height = 500,
scrollWidth = 300,
scrollHeight = 500,
horizontalScrollDisabled = true,
listener = scrollListener
}
local button = {}
local yCount = 0
for i = 1 , 11 do
button[i] = widget.newButton{
label = "Button " .. i,
left = 0,
id = button[i],
top = yCount,
width = 300,
height = 100,
defaultFile = "menuButton.png",
onEvent = handleButtonEvent
}
yCount = yCount + 100
scrollView:insert(button[i])
end
--local background=display.newRect(160, 270, 320, 510)
--scrollView:insert( background )
local menu=display.newImageRect("menu2.png", 90, 50)
menu.x=50
menu.y=-15
function menu:touch(event)
if event.phase=="began" then
--local illBeBack=audio.play(terminator,{channel=1, loops=0, fadein=0})
display.remove(menu)
display.remove(taskBar)
display.remove(background)
taskBar = nil
background = nil
menu = nil
storyboard.gotoScene("menu")
end
return true
end
menu:addEventListener("touch", menu)
end
--Button Event Handler
local function handleButtonEvent( event )
local phase = event.phase
if ( phase == "moved" ) then
local dy = math.abs( ( event.y - event.yStart ) )
-- If the touch on the button has moved more than 10 pixels,
-- pass focus back to the scroll view so it can continue scrolling
if ( dy > 10 ) then
scrollView:takeFocus( event )
end
end
return true
end
Try passing the event.phase into scrollView like this:
scrollView:takeFocus(event.phase)
The problem was solved by removing 'local' from the 'handleButtonEvent' and 'scrollListener' functions, along with removing 'local' from the 'scrollView' widget
So it appears that in corona, or at least the program I am making, that globals must be used a lot more than what they should be, unless someone else has a solution.

Score activated when button is pressed does not work, Corona sdk

I would like the score to increase only when this button is pressed. However when I tried running my code the score did not change... Any ideas?
thanks in advance!
here is my code:
score = 0
local scoreNumber = display.newText(score, 200, 30, nil, 20)
scoreNumber.xScale = 1.2
scoreNumber.yScale = 1.2
local scoreText = display.newText("score:", 150, 30, nil, 20)
scoreText.xScale = 1.2
scoreText.yScale = 1.2
local buttonPressed = false
local myButton = display.newRect(50,50,100,100)
local function scoretimer(event)
if buttonPressed then
score = score + 1
scoreNumber.text = score
end
end
local function buttonPressed(event)
if event.phase == "began" then
buttonPressed = true
elseif event.phase == "ended" then
buttonPressed = false
end
return true
end
myButton:addEventListener("touch", buttonPressed)
Runtime:addEventListener("enterFrame", scoretimer)
First you declare:
local buttonPressed = false
end then you declare it again as a function:
local function buttonPressed(event)
Rename your function and everything should go fine

Calling functions passed as arguments in Lua

I have this code
Option = { }
function Option.nothing( )
local self = { isNone = true, isSome = false }
function self:orElse( alt )
return alt
end
function self:map( f )
return Option.nothing( )
end
function self:exec( f )
end
function self:maybe( alt, f )
return alt
end
return self
end
function Option.just( val )
local self = { isNone = false, isSome = true }
local value = val
function self:orElse( alt )
return value
end
function self:map( f )
return Option.just( f(value) )
end
function self:exec( f )
f( value )
end
function self:maybe( alt, f )
return f(value)
end
return self
end
function printOpt( opt )
local str = opt.maybe( "Nothing", function(s) return "Just " .. s end )
print( str )
end
x = Option.nothing( )
y = Option.just( 4 )
printOpt(x)
printOpt(y)
But I keep getting 'attempt to call local 'f' (a nil value)' here:
function self:maybe( alt, f )
return f(value)
end
It seems I'm having trouble calling a function passed as a argument.
You declared the function as self:maybe(), but you're calling it as opt.maybe(). You should call it as opt:maybe().
Declaring it as self:maybe(alt, f) is equivalent to declaring it as self.maybe(self, alt, f). So if you call it with a . you need 3 args. You're passing 2, so self ends up as "Nothing", and alt ends up as the function object.
However, by calling it as opt:maybe("Nothing", f) this is equivalent to saying opt.maybe(opt, "Nothing", f) which provides the required 3 args.

Resources