Quick Links: Download Gideros Studio | Gideros Documentation | Gideros Development Center | Gideros community chat | DONATE
accessing a variable which exist in another file — Gideros Forum

accessing a variable which exist in another file

loves_oiloves_oi Member
edited September 2012 in General questions
This is my main.lua
-- Usual SceneManager stuff.
sceneManager = SceneManager.new({
--	["logoScreen"] = logoScreen,
--	["menuScreen"] = menuScreen,
--	["gameScreen"] = gameScreen,
--	["levelEndScreen"] = levelEndScreen,
--	["nextLevelScreen"] = nextLevelScreen,
	["optionScreen"] = optionScreen
})
--add manager to stage
stage:addChild(sceneManager)
 
--start start scene
sceneManager:changeScene("optionScreen", 1, SceneManager.flipWithFade, easing.outBack)
 
local loader = UrlLoader.new('<a href="http://localhost/write.php'" rel="nofollow">http://localhost/write.php'</a>)
 
local function onComplete(event)
 
	local myString=event.data      -- We got the string here.
 
        ......
 
	function how_many(searchAt,letter)
		local i2 = 1
		local a = 0
		while (i2 < string.len(searchAt)+1)
		do
			if(string.sub(searchAt,i2,i2) == letter)
			then
					a = a + 1 
					i2 = i2 + 1
			else
				i2 = i2 + 1
			end	
		end 
		return a
	end
	...........
	function getH()
		h = how_many(echoString,'\n')  
		return h
	end
end
 
local function onError()
    print("error")
end
 
local function onProgress(event)
    print("progress: " .. event.bytesLoaded .. " of " .. event.bytesTotal)
end
 
loader:addEventListener(Event.COMPLETE, onComplete)
loader:addEventListener(Event.ERROR, onError)
loader:addEventListener(Event.PROGRESS, onProgress)
and this is options.lua
function optionScreen:init()
	......
	h = getH() -----!!!PROBLEM!!!
	while(h<8)
	do
		print ("00")
		h = h + 1
	end
I want to use the value h which is found in main.lua.But it doesn't work:S How can i do it?
Thanks in advance.

Comments

  • "h" if not declared as local will be global and accessible as soon as it's been "seen" by the lua compiler (otherwise it'll get created the first time it's read and be assigned a value of nil).

    You can either right click on the file "options.lua" in the IDE and set a code dependency so that the file containing the correct definition of "h" is parsed BEFORE "options.lua" (check the call order tab to see which order your code is parsed in) or (IMHO a better solution) would be to move the definition of "h" and any other global variables, into a file called "init.lua" which is guaranteed by Gideros to be the first file processed (main.lua is usually the last).

    Also FWIW - "h" is a very poor name for a global - it's way to easy to get it confused later, or mistaken for a local etc etc - I would always recommend naming globals in UPPER_CASE and making them descriptive - that way you can see instantly when looking at your code which is which (just my $0.02)

    Likes: loves_oi

    WhiteTree Games - Home, home on the web, where the bits and bytes they do play!
    #MakeABetterGame! "Never give up, Never NEVER give up!" - Winston Churchill
    +1 -1 (+1 / -0 )Share on Facebook
  • ok. then how can i use h value outside the onComplete function?
  • talistalis Guru
    edited September 2012
    as @techdojo said just make a file called init.lua and define all your global variables there.
    After it just adreess them whereever you want. It doesn't matter in which file is or function.
    Just be sure that do not redefine any global variable again as local variable in any of your lua files or function again.
    Possible init.lua file:
    ---------------------------------------------------------
    ------------------------Global Values----------------------
    ----------------------------------------------------------
     
    --- X,Y coordinate of my Texts
    GlbTextX=60
    GlbTextY=60
     
    ---Boolean Global variables
    GlbMusicplay=      false
    GlbSfxplay     =     false
     
    ---Sprites
    GlbBackground	= Bitmap.new(Texture.new("bg.jpg"),true)	
     
    ----------------------End Of Global Values-----------------
    I am always naming my global variables starting with Glb so i will not override them accidentally.
    You can also name your sprites with starting Spr for example it will enhance the readibility of your code. like a global sprite background will be:
    GlbSprBackground
    but a local sprite of background will be just:
    SprBackground

    Or another example your buttons can start with Btn, your text strings can start with Str etc etc:D

    Likes: loves_oi

    +1 -1 (+1 / -0 )Share on Facebook
  • I defined the global variable in init.lua. OK. After running,firstly, a new assignment should be done in main.lua. I have to use the new value of the global variable in optionScreen.lua . But in optionScreen.lua , the value of the global variable is the old value :S
  • talistalis Guru
    edited September 2012
    @loves_oi you can not predict which lua file will be committed first only it is sure that inits.lua will be the first one so in your code do not depend on the fact that main.lua assignment will be earlier than optionScreen.lua . Make calculations of your global in the init function of optionsscreen lua . So in this way you will be sure that you will get the new value not the the old one.
  • loves_oiloves_oi Member
    edited September 2012
    I have to mix onComplete function and OptionScreen.lua. It seems so confusing. I can't overcome this problem :( This is the mixed code:

    This is main.lua
     
    sceneManager = SceneManager.new({
    --	["logoScreen"] = logoScreen,
    --	["menuScreen"] = menuScreen,
    --	["gameScreen"] = gameScreen,
    --	["levelEndScreen"] = levelEndScreen,
    --	["nextLevelScreen"] = nextLevelScreen,
    	["optionScreen"] = optionScreen
    })
     
    --add manager to stage
    stage:addChild(sceneManager)
     
    --start start scene
    sceneManager:changeScene("optionScreen", 1, SceneManager.flipWithFade, easing.outBack)

    This is optionscreen.lua
    --[[
    *************************************************************
     * This script is developed by Scouser, it uses modules 
     * created by other developers but I have made minor / subtle
     * changes to get the effects I required.
     * Feel free to distribute and modify code, 
     * but keep reference to its creator
    **************************************************************
    ]]--
     
    optionScreen = Core.class(Sprite)
     
    local imgBase = getImgBase()
    local font = getFont()
     
    local checkX = 60
    local sliderX = 240
    local gap = 70
     
    local col = {r=243/255,g=206/255,b=0,a=1}
     
    local soundSlider
    local musicSlider
    local redSlider
     
     
    local loader = UrlLoader.new("<a href="http://localhost/write.php&quot" rel="nofollow">http://localhost/write.php&quot</a><img class="emoji" src="http://forum.giderosmobile.com/resources/emoji/wink.png" title=";)" alt=";)" height="20" />
     
     
     
     
     
    function optionScreen:init()
    	--here we'd probably want to set up a background picture
    	local screen = Bitmap.new(Texture.new(imgBase.."opt_back.png"))
    	self:addChild(screen)
    	screen:setPosition(0,0)
     
    	local txtY = 100
     
    	local function onComplete(event)
    		local myString=event.data      -- We got the string here.
    			--local timer = Timer.new(1000, 8)
    		--timer:addEventListener(Event.TIMER, onComplete)---
    		local length = string.len(myString)
    		local i = 1
    		local echoString = ""
    		while (i < length+1) do
     
    			echoString = echoString .. string.sub(myString,i,i)
     
    			i = i+1;
    		end
    		print (echoString)
    		function how_many(searchAt,letter)
    			local i2 = 1
    			local a = 0
    			while (i2 < string.len(searchAt)+1)
    			do
    				if(string.sub(searchAt,i2,i2) == letter)
    				then
    						a = a + 1 
    						i2 = i2 + 1
    				else
    					i2 = i2 + 1
    				end	
    			end 
    			return a
    		end
     
    		function getH()
    			h = how_many(echoString,'\n')  
    			return h
    		end
     
    		h = how_many(echoString,'\n')
    		print("h1 = " .. h)
    		----[[
    		i=1
    		k=0
    		local tit = ""
    		local taken = {}
    		local theText = {}
    		while (k < h)
    		do
    			theText[k] = TextField.new(nil, "placeholder")
    			theText[k]:setPosition(150,125+k*50)
    			theText[k]:setTextColor(0x007B25)
    			theText[k]:setScaleX(5)  
    			theText[k]:setScaleY(5)
    			stage:addChild(theText[k])
    			while (not(string.find(string.sub(echoString,i,i), "\t")))        -- take the tit 
    				do
    					tit = tit ..  string.sub(echoString,i,i)
    					taken[1] = tit
    					i = i + 1
    				end
    			tit = ""
    			if (string.find(string.sub(echoString,i,i), "\t"))
    				then 
    					i = i + 1
    				end
     
    			while (not(string.find(string.sub(echoString,i,i), "\t")))        -- take the tit 
    				do
    					tit = tit ..  string.sub(echoString,i,i)
    					taken[2] = tit
    					i = i + 1
    				end
    			tit = ""
    			if (string.find(string.sub(echoString,i,i), "\t"))
    				then 
    					i = i + 1
    				end
     
    			while (not(string.find(string.sub(echoString,i,i), "\n")))        -- take the tit 
    				do
    					tit = tit ..  string.sub(echoString,i,i)
    					taken[3] = tit
    					i = i + 1
    				end
    			tit = ""
    			if (string.find(string.sub(echoString,i,i), "\n")) or (string.find(string.sub(echoString,i,i), nil))
    				then 
    					print "---------------------bitti------------------------"
    					i = i + 1
    				end
    			print (taken[1],taken[2],taken[3])
    			theText[k]:setText(taken[2])	
    			k = k + 1
    		end	
    		--]]
    	end
     
     
    	local index = h
    	cbox = {}
    	print("h = " .. h)
    	print("index = " .. index)
    	while(index<5)
    	do
    		print (index)
    		index = index + 1
    	end
     
    	cbox[1] = checkBox.new(checkX, txtY, "Music", col,
    		function(this)
    			local state = this:getCheck()
    			if state then settings.musicOn()
    			else settings.musicOff()
    			end
    		end
    	)
    	screen:addChild(cbox[1])
    	cbox[1]:setCheck(settings.getMusicState())
     
    	txtY = txtY + gap
    	-- Sound On / Off
    	cbox[2] = checkBox.new(checkX, txtY, "Sound FX", col, 
    		function(this)
    			local state = this:getCheck()
    			if state then settings.soundOn() 
    			else settings.soundOff()
    			end
    		end	
    	)
    	screen:addChild(cbox[2])
    	cbox[2]:setCheck(settings.getSoundState())
     
    	txtY = txtY + gap
    	-- Autosave On / Off
    	cbox[3] = checkBox.new(checkX, txtY, "Autosave", col, 
    		function(this)
    			local state = this:getCheck()
    			if state then settings.autosaveOn() 
    			else settings.autosaveOff()
    			end
    		end
    	)
    	screen:addChild(cbox[3])
    	cbox[3]:setCheck(settings.getAutosaveState())
     
    	txtY = txtY + gap
     
    	self:removeEventListener("exitEnd", self.onExitEnd)
     
    	local function onError()
        print("error")
    	end
     
    	local function onProgress(event)
    		print("progress: " .. event.bytesLoaded .. " of " .. event.bytesTotal)
    	end
     
    	loader:addEventListener(Event.COMPLETE, onComplete)
    	loader:addEventListener(Event.ERROR, onError)
    	loader:addEventListener(Event.PROGRESS, onProgress)
     
    end
     
     
     
     
    -- Let's get rid of all of the elements shall we. This is strictly not required
    -- but I thought I'd put it in for completeness
    function optionScreen:onExitEnd()
    	self:removeEventListener("exitEnd", self.onExitEnd)
    	redSlider:onExitEnd()
    	greenSlider:onExitEnd()
    	blueSlider:onExitEnd()
    	musicSlider:onExitEnd()
    	soundSlider:onExitEnd()
     
    	soundChk:onExitEnd()
    	musicChk:onExitEnd()
    	autosaveChk:onExitEnd()
     
    	collectgarbage()
    end
     
     
    function optionScreen:adjustRed(this) 
    	col.r = (redSlider:getPos()*2.55)/255 
    	redSlider:setCol({r=col.r,g=0,b=0,a=1})
    	musicSlider:setCol(col)
    	soundSlider:setCol(col)
    	autosaveChk:setCol(col)
    	soundChk:setCol(col)
    	musicChk:setCol(col)
    end
     
    function optionScreen:adjustGreen(this) 
    	col.g = (greenSlider:getPos()*2.55)/255 
    	greenSlider:setCol({r=0,g=col.g,b=0,a=1})
    	musicSlider:setCol(col)
    	soundSlider:setCol(col)
    	autosaveChk:setCol(col)
    	soundChk:setCol(col)
    	musicChk:setCol(col)
    end
     
    function optionScreen:adjustBlue(this) 
    	col.b = (blueSlider:getPos()*2.55)/255 
    	blueSlider:setCol({r=0,g=0,b=col.b,a=1})
    	musicSlider:setCol(col)
    	soundSlider:setCol(col)
    	autosaveChk:setCol(col)
    	soundChk:setCol(col)
    	musicChk:setCol(col)
    end
  • loves_oiloves_oi Member
    edited September 2012
    And this is the code before mixing :

    main.lua
    local loader = UrlLoader.new('<a href="http://localhost/write.php'" rel="nofollow">http://localhost/write.php'</a>)
     
     
    local function onComplete(event)
     
    	local myString=event.data      -- We got the string here.
     
            --local timer = Timer.new(1000, 8)
    	--timer:addEventListener(Event.TIMER, onComplete)---
     
    	local length = string.len(myString)
    	local i = 1
     
    	local echoString = ""
    	while (i < length+1) do
     
    		echoString = echoString .. string.sub(myString,i,i)
     
    		i = i+1;
    	end
    	print (echoString)
    	--theText:setText(echoString)
    	------------------------------------------------------------------------------------------------
    	--[[
    	while (not(string.find(string.sub(myString,i,i), "^%w+$")))    --pass the first limiters
    		do	
    			i = i + 1
    	end
     
    	]] 
    	function how_many(searchAt,letter)
    		local i2 = 1
    		local a = 0
    		while (i2 < string.len(searchAt)+1)
    		do
    			if(string.sub(searchAt,i2,i2) == letter)
    			then
    					a = a + 1 
    					i2 = i2 + 1
    			else
    				i2 = i2 + 1
    			end	
    		end 
    		return a
    	end
     
    	function getH()
    		h = how_many(echoString,'\n')  
    		return h
    	end
     
    	h = how_many(echoString,'\n')
    	print("h1 = " .. h)
    	----[[
    	i=1
    	k=0
    	local tit = ""
    	local taken = {}
    	local theText = {}
    	while (k < h)
    	do
    		theText[k] = TextField.new(nil, "placeholder")
    		theText[k]:setPosition(150,125+k*50)
    		theText[k]:setTextColor(0x007B25)
    		theText[k]:setScaleX(5)  
    		theText[k]:setScaleY(5)
    		stage:addChild(theText[k])
     
     
    		while (not(string.find(string.sub(echoString,i,i), "\t")))        -- take the tit 
    			do
    				tit = tit ..  string.sub(echoString,i,i)
    				taken[1] = tit
    				i = i + 1
    			end
    		tit = ""
    		if (string.find(string.sub(echoString,i,i), "\t"))
    			then 
    				i = i + 1
    			end
     
    		while (not(string.find(string.sub(echoString,i,i), "\t")))        -- take the tit 
    			do
    				tit = tit ..  string.sub(echoString,i,i)
    				taken[2] = tit
    				i = i + 1
    			end
    		tit = ""
    		if (string.find(string.sub(echoString,i,i), "\t"))
    			then 
    				i = i + 1
    			end
     
    		while (not(string.find(string.sub(echoString,i,i), "\n")))        -- take the tit 
    			do
    				tit = tit ..  string.sub(echoString,i,i)
    				taken[3] = tit
    				i = i + 1
    			end
    		tit = ""
    		if (string.find(string.sub(echoString,i,i), "\n")) or (string.find(string.sub(echoString,i,i), nil))
    			then 
    				print "---------------------bitti------------------------"
    				i = i + 1
    			end
    		print (taken[1],taken[2],taken[3])
    		theText[k]:setText(taken[2])	
    		k = k + 1
    	end	
    	--]]
    end
     
     
    local function onError()
        print("error")
    end
     
    local function onProgress(event)
        print("progress: " .. event.bytesLoaded .. " of " .. event.bytesTotal)
    end
     
    loader:addEventListener(Event.COMPLETE, onComplete)
    loader:addEventListener(Event.ERROR, onError)
    loader:addEventListener(Event.PROGRESS, onProgress)
     
     
    sceneManager = SceneManager.new({
    --	["logoScreen"] = logoScreen,
    --	["menuScreen"] = menuScreen,
    --	["gameScreen"] = gameScreen,
    --	["levelEndScreen"] = levelEndScreen,
    --	["nextLevelScreen"] = nextLevelScreen,
    	["optionScreen"] = optionScreen
    })
     
    --add manager to stage
    stage:addChild(sceneManager)
     
    --start start scene
    sceneManager:changeScene("optionScreen", 1, SceneManager.flipWithFade, easing.outBack)
    optionscreen.lua
    --[[
    *************************************************************
     * This script is developed by Scouser, it uses modules 
     * created by other developers but I have made minor / subtle
     * changes to get the effects I required.
     * Feel free to distribute and modify code, 
     * but keep reference to its creator
    **************************************************************
    ]]--
     
    optionScreen = Core.class(Sprite)
     
    local imgBase = getImgBase()
    local font = getFont()
     
    local checkX = 60
    local sliderX = 240
    local gap = 70
     
    local col = {r=243/255,g=206/255,b=0,a=1}
     
    local soundSlider
    local musicSlider
    local redSlider
     
    function optionScreen:init()
    	--here we'd probably want to set up a background picture
    	local screen = Bitmap.new(Texture.new(imgBase.."opt_back.png"))
    	self:addChild(screen)
    	screen:setPosition(0,0)
     
    	local txtY = 100
     
    	local index = h
    	cbox = {}
    	print("h = " .. h)
    	print("index = " .. index)
    	while(index<5)
    	do
    		print (index)
    		index = index + 1
    	end
     
    	cbox[1] = checkBox.new(checkX, txtY, "Music", col,
    		function(this)
    			local state = this:getCheck()
    			if state then settings.musicOn()
    			else settings.musicOff()
    			end
    		end
    	)
    	screen:addChild(cbox[1])
    	cbox[1]:setCheck(settings.getMusicState())
     
    	txtY = txtY + gap
    	-- Sound On / Off
    	cbox[2] = checkBox.new(checkX, txtY, "Sound FX", col, 
    		function(this)
    			local state = this:getCheck()
    			if state then settings.soundOn() 
    			else settings.soundOff()
    			end
    		end	
    	)
    	screen:addChild(cbox[2])
    	cbox[2]:setCheck(settings.getSoundState())
     
    	txtY = txtY + gap
    	-- Autosave On / Off
    	cbox[3] = checkBox.new(checkX, txtY, "Autosave", col, 
    		function(this)
    			local state = this:getCheck()
    			if state then settings.autosaveOn() 
    			else settings.autosaveOff()
    			end
    		end
    	)
    	screen:addChild(cbox[3])
    	cbox[3]:setCheck(settings.getAutosaveState())
     
    	txtY = txtY + gap
     
    	self:removeEventListener("exitEnd", self.onExitEnd)
    end
     
    -- Let's get rid of all of the elements shall we. This is strictly not required
    -- but I thought I'd put it in for completeness
    function optionScreen:onExitEnd()
    	self:removeEventListener("exitEnd", self.onExitEnd)
    	redSlider:onExitEnd()
    	greenSlider:onExitEnd()
    	blueSlider:onExitEnd()
    	musicSlider:onExitEnd()
    	soundSlider:onExitEnd()
     
    	soundChk:onExitEnd()
    	musicChk:onExitEnd()
    	autosaveChk:onExitEnd()
     
    	collectgarbage()
    end
     
     
    function optionScreen:adjustRed(this) 
    	col.r = (redSlider:getPos()*2.55)/255 
    	redSlider:setCol({r=col.r,g=0,b=0,a=1})
    	musicSlider:setCol(col)
    	soundSlider:setCol(col)
    	autosaveChk:setCol(col)
    	soundChk:setCol(col)
    	musicChk:setCol(col)
    end
     
    function optionScreen:adjustGreen(this) 
    	col.g = (greenSlider:getPos()*2.55)/255 
    	greenSlider:setCol({r=0,g=col.g,b=0,a=1})
    	musicSlider:setCol(col)
    	soundSlider:setCol(col)
    	autosaveChk:setCol(col)
    	soundChk:setCol(col)
    	musicChk:setCol(col)
    end
     
    function optionScreen:adjustBlue(this) 
    	col.b = (blueSlider:getPos()*2.55)/255 
    	blueSlider:setCol({r=0,g=0,b=col.b,a=1})
    	musicSlider:setCol(col)
    	soundSlider:setCol(col)
    	autosaveChk:setCol(col)
    	soundChk:setCol(col)
    	musicChk:setCol(col)
    end
  • @loves_oi you can not predict which lua file will be committed first only it is sure that inits.lua will be the first one so in your code do not depend on the fact that main.lua assignment will be earlier than optionScreen.lua . Make calculations of your global in the init function of optionsscreen lua . So in this way you will be sure that you will get the new value not the the old one.
    Main.lua will (should) be the last file parsed - as this is "supposed" to be the entry point of your app it means that all the classes, tables etc *should* exist and be initialised BEFORE you access them in main.lua

    @loves_oi - the problem is that the function getH doesn't exist or get called until the onComplete function is called (as these are defined inside it). As the OptionsScreen:init method is called first you are picking up the fact that at this point "h" doesn't actually exist so lua creates it (as a global) and gives it a default value of nil.

    I would suggest liberally adding some print() statements to your code so you can understand the flow of code - as soon as you see that you'll begin to understand why it's not working. Rather than me just tell you a "fix" now, it's better that you try and understand the "why" so you won't make this mistake in the future - think of it a bit like the difference between "giving a man a fish" and "teaching a man how to fish".

    With all the callbacks etc - the flow of code in Lua CAN be a little difficult to trace - just remember the KISS principal as much as possible.

    Likes: loves_oi

    WhiteTree Games - Home, home on the web, where the bits and bytes they do play!
    #MakeABetterGame! "Never give up, Never NEVER give up!" - Winston Churchill
    +1 -1 (+1 / -0 )Share on Facebook
  • @loves_oi,
    look in the project window. The order in which the lua files appear is how they are executed. Gideros runs each one of the files, if you want to control running them, use the require function to trigger the loading of that file and in the project set them as excluded from execution.

    Likes: loves_oi

    twitter: @ozapps | http://www.oz-apps.com | http://howto.oz-apps.com | http://reviewme.oz-apps.com
    Author of Learn Lua for iOS Game Development from Apress ( http://www.apress.com/9781430246626 )
    Cool Vizify Profile at https://www.vizify.com/oz-apps
    +1 -1 (+1 / -0 )Share on Facebook
Sign In or Register to comment.