通过迭代创建按钮?

lenim 发布于 2019-03-09 button 最后更新 2019-03-09 14:37 0 浏览

我一直在使用Corona引擎,我试图通过循环创建多个按钮,而不是明确地创建每个单独的按钮。问题是循环似乎只生成一个按钮,表明它只是迭代一次。 以下是我到目前为止... 更新

--> Create Level Selection:
local levelSelectionGroup = display.newGroup( );
--> Level Selected:
local function levelSelected()
    print(id);
end
--> Button Creation:
local function createLevelSelection()
    local levelsToBeMade = 30; -- Ignore these random numbers for now.
    local positionX = 1; -- Ignore again.
    local positionY = 1; -- Ignore again.
for buttonNumber=1, levelsToBeMade do
        print(buttonNumber);
positionX = (positionX + 10); -- Ignore again.
        positionY = (positionY + 10); -- Ignore again.
levelButton[buttonNumber] = widget.newButton{ 
            id = buttonNumber,
            label = buttonNumber,
            default = "images/levelButton.png",
            over = "images/levelButtonPressed.png",
            width = 50,
            height = 50,
            onRelease = levelSelected
        }
levelButton[buttonNumber].x = positionX;
        levelButton[buttonNumber].y = positionY;
levelSelectionGroup:insert(levelButton[buttonNumber]);
    end
end
控制台状态...
attempt to index global 'levelButton' (a nil value)
已邀请:

rut

赞同来自:

(对不起,我不知道Corona所以这可能不适用。) 什么是levelButton,你确定它存在吗?也许它应该是levelButtons? 如果确实如此,请检查以确保newButton()实际上按预期返回一个表:print(levelButton[buttonNumber])

jenim

赞同来自:

您可能需要重新考虑算法并在循环时更改此算法。 如果要生成的级别数保持不变,则可能需要执行for循环,直到达到第31个循环。

 for i=1,levelstToBeMade  do
levelstToBeMade = (levelsToBeMade - 1); -- Ignore numbers.
    positionX = positionX + 10; -- Ignore numbers.
    positionY = postionY + 10; -- Ignore numbers.
levelButton[levelsToBeMade] = widget.newButton{ 
        id = levelsToBeMade,
        label = levelsToBeMade,
        default = "images/levelButton.png",
        over = "images/levelButtonPressed.png",
        width = 50,
        height = 50,
        onRelease = levelSelected
    }
levelButton[levelsToBeMade].x = positionX;
    levelButton[levelsToBeMade].y = positionY;
end
希望这可以帮助。 干杯

yet

赞同来自:

我想你的变量或范围可能有问题。因此,请确保levelsToBeMade变量和positionX和positionY变量是正确的。如果你完全确定,这应该有效:(我没有看到你的代码有什么问题,但是,我觉得for循环更可信。)

for i=1, levelsToBeMade do
print( "levelButton+1).." will be created." )
positionX = positionX + 10; -- Ignore numbers.
    positionY = postionY + 10; -- Ignore numbers.
levelButton[#levelButton+1] = widget.newButton{ 
        id = #levelButton,
        label = #levelButton,
        default = "images/levelButton.png",
        over = "images/levelButtonPressed.png",
        width = 50,
        height = 50,
        onRelease = levelSelected
    }
levelButton[#levelButton].x = positionX;
    levelButton[#levelButton].y = positionY;
end
如果它不起作用,只需检查控制台,看看循环是否执行了所需的时间。 最后编辑: 哦,没注意到。你以前从未创建过levelButton表!在开始创建关卡按钮之前,您应该创建如下:local levelButton = {},在for循环之外