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)
4

3 回答 3

1

我猜你的变量或范围可能有问题。所以要确保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 = {}, at outside of for loop

于 2013-04-11T21:29:20.233 回答
0

(抱歉,我不了解 Corona,所以这可能不适用。)

什么是levelButton,你确定它存在吗?也许应该是levelButtons

如果这没问题,请检查以确保newButton()实际按预期返回表:print(levelButton[buttonNumber])

于 2013-04-13T18:35:44.447 回答
0

您可能需要重新考虑您的算法并更改此 while 循环。

如果要生成的级别数保持不变,您可能需要执行一个 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

希望这可以帮助。

干杯

于 2013-04-11T16:27:36.863 回答