Game Menu Functions

Hi Community,

I’m trying to code my level selection screen for my game. Currently, I have a large amount of buttons triggering individual functions to load each level.

Example:

local function playLevel1 (level)  
 print("Play Level 1")  
 director:changeScene ("level\_1", "overFromBottom")  
end  
local function playLevel2 (event)  
 print("Play Level 2")  
 director:changeScene ("level\_2", "overFromBottom")  
end  
local function playLevel3 (event)  
 print("Play Level 3")  
 director:changeScene ("level\_3", "overFromBottom")  
end  

…and so on.

Is there anyway to cram all this into a single function? I’d like to be able to reduce the memory load from ~40 repetitive functions. [import]uid: 100403 topic_id: 22003 reply_id: 322003[/import]

Well I’m not totally clear on your setup but here’s an example of how you could eliminate the repeat functions and condense your code substantially.

Let’s assume you’re using Widget buttons:

[code]
local function onLevelSelect(event)
local levelName = event.target.id
print(“Play:”, levelName)
director:changeScene(levelName, “overFromBottom”)
end

local level1 = widget.newButton{
id = “level_1”,
width = 100, height = 45,
left = 110, top = 100,
label = “Level 1”,
onRelease = onLevelSelect
}

local level2 = widget.newButton{
id = “level_2”,
width = 100, height = 45,
left = 110, top = 200,
label = “Level 2”,
onRelease = onLevelSelect
}

local level3 = widget.newButton{
…[/code]

Even better, use a table with the number of levels and their x/y positions to create all the buttons in a for loop, since they’re all almost identical. Let us know if this wasn’t what you were looking for. [import]uid: 87138 topic_id: 22003 reply_id: 87459[/import]