So I am relatively new, but have been trying to develop good (or at least not terrible) coding habits. I’ve read a lot of material on using modular coding practices to improve organization, efficiency, and reduce globals within my code. I could use some help trying to sort out the following situation:
I can break it down to 2 files … The 1st contains the information for my level and makes calls to the 2nd file. The 2nd contains objects and the functions that control them which will be used many times in multiple levels. I want to use file 1 to call a “door” and “switch” object (stored in file 2). When I touch the switch, I want the door to move.
File 1 is “main.lua”
[lua]
–Main.lua
local gamefunctions = require( “gamefunctions” )
local door = gamefunctions.newDoor()
local doorSwitch = gamefunctions.newDoorSwitch()
[/lua]
File 2 is “gamefunctions.lua”
[lua]
–gamefunctions.lua
local M = {}
local function newDoor()
local door = display.newRect( 540, 180, 10, 80 )
door:setFillColor( 0, 0, 250 )
physics.addBody(door, “static”, {filter={categoryBits = 10, maskBits = 3} } )
return door
end
M.newDoor = newDoor
local function newDoorSwitch()
local doorSpriteSheet = sprite.newSpriteSheet(“images/doorSwitchSpriteSheetTest.png”, 64, 106)
local doorSpriteSet = sprite.newSpriteSet(doorSpriteSheet, 1, 3)
sprite.add( doorSpriteSet, “left”, 1, 3, 200, 1 )
–sprite.add( doorSpriteSet, “right”, 2, 1, 200, 0 )
local doorSwitch = sprite.newSprite ( doorSpriteSet )
doorSwitch.x = 460
doorSwitch.y = 130
doorSwitch.xScale = .5
doorSwitch.yScale = .5
– Raise door when switch is triggered
local function exitDoor( event )
if door.y == 220 then --**CODE FAILS HERE WHEN SWITCH IS TOUCHED**
transition.to( door, { time=1500, y=door.y - 70 } )
doorSwitch:prepare(“left”)
doorSwitch:play()
elseif door.y == 150 then
transition.to( door, { time=1500, y=door.y + 70 } )
end
end
doorSwitch:addEventListener( “touch”, exitDoor )
return doorSwitch
end
M.newDoorSwitch = newDoorSwitch
return M
[/lua]
Obviously I’ve left a lot out, but this is what happens:
-The door and doorSwitch objects are created
- I “touch” the doorSwitch and the listener sends me to “exitDoor” function
- Code fails, I guess because “door” doesn’t exist within that scope (error is: “attempt to index global ‘door’ (a nil value)”)
A “door” object was created within the main.lua file … How do I set things up so that I have access to that object to make it move? I can’t reference back to main.lua from my gamefunctions.lua since it would defeat the purpose of that file (designed to be reused over multiple level files).
Also, why does the error say that “door” is a global? … I thought I defined it as local?
FYI, these are 2 of the main examples I was using when setting up my code:
http://www.coronalabs.com/blog/2011/08/12/tutorial-simple-modular-coding-technique/
http://www.coronalabs.com/blog/2011/09/05/a-better-approach-to-external-modules/
Thanks! [import]uid: 146966 topic_id: 35964 reply_id: 335964[/import]