Search code examples
luacocos2d-x

Lua Ide Cocos. Table almost working and then not working in a weird way


This is a short excerpt of the offending code. The summary is that 3 ccsprite are put into a lua table and then I attempt to add those nodes to the cclayer in the same fashion as the example I'm working from. The error I get is:

addChild has wrong number of arguments: 0, was expecting 3 

So perhaps I could believe the table entry disappears on its way to add function with some creative interpretation of Lua's bizarre scoping ideology, but on the other hand if I were to add a table entry of 4 to the table before I attempt to add the table entry sprites (the code to do this is there and commented out) I get this error:

[LUA-print] LUA ERROR: [string ".\GameScene.lua"]:101: 
     error in function 'lua_cocos2dx_Node_addChild'.
     argument #1 is 'number'; 'cc.Node' expected. 

So I'm faced with the discovery that addChild is perfectly happy with swallowing 3 sprites, but declares that their existence represents an argument count of 0. I am new to Lua but this is an error that is unreasonably opaque. I do not understand. Note also that in the C++ that lua is feeding off, addchild() is a function of just one argument, not 3, much less 0.

Pens = {}

for i = 1, 3 do  -- The range includes both ends.
    local bg = cc.Sprite:create("farm.jpg")
    local spriteSize = bg:getContentSize()
    local heightScale = frameSize.height/spriteSize.height
    local lengthScale = frameSize.width/spriteSize.width

    bg:setPosition(i*(self.origin.x + self.visibleSize.width / 2),
     i*(self.origin.y + self.visibleSize.height / 2))
    bg:setScale(lengthScale/2,heightScale/2)

    Pens[i] = bg --.newKey = {i,bg}
    print(Pens[i])
end

--Pens[4] = 4
--print(Pens[4])
print("bleh")

print(Pens[2])

for i, v in ipairs(Pens) do
    print(v)
    layerWorld.addChild(v)
end 

Even simpler code with identical behavior:

Pens = {}

for i = 1, 5 do

    local spriteLand = cc.Sprite:create("land.png")
    spriteLand:setPosition(i*20,i*20)
    Pens[i] = spriteLand

end

for i, v in ipairs(Pens) do
    print(v)
    layerWorld.addChild(v)
end 

Solution

  • I can't explain the problem but perhaps this is a solution. In the for loop, i is the index and v is the value, so you needn't index the table to get the value. Simply try:

    for i, v in ipairs(Pens) do
        print(v)
        layerWorld.addChild(v)
    end