Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Please help me to simplify this code

edited August 2012 in General Posts: 52
function setup()
    obj0=456
    obj1=9899
    obj2=5453
    obj3=54
    obj5=3232
    obj6=232
    obj7="hello"
    obj8=889
    target=1
end
function draw()
    --//when user input "target" detected//--
    if target==0 then
        print(obj0)
    elseif target==1 then
        print(obj1)
    elseif target==2 then
        print(obj2)
    elseif target==3 then
        print(obj3)
    elseif target==4 then
        print(obj4)
    elseif target==5 then
        print(obj5)
    elseif target==6 then
        print(obj6)
    elseif target==7 then
        print(obj7)
    elseif target==8 then
        print(obj8)
    end
end

Now there are only 8 objs,but if I add to 50,I can't imagine how many "elseif" I have to use.Is there any thing like"obj.target" in lua? Thanks!

Tagged:

Comments

  • Posts: 52

    Oh,Sorry for the terrible layout.It's looks good on my draft.

  • SimeonSimeon Admin Mod
    Posts: 5,200

    You should use a table:

    function setup()
        objects = {}
        target = 1
    
        -- Add your objects
        addObject( 456 )
        addObject( 9899 )
        addObject( "hello" )
        addObject( 123 )
        -- ... and so on
    end
    
    function addObject( value )
        table.insert( objects, value )
    end
    
    function draw()
        -- when user input "target" detected
        print( objects[target] )
    end
    
  • Posts: 52

    Awesome!Thanks a lot!
    Another question,I still couldn't figure out where to put my picture in xcode when i use sprite like this

    sprite("Documents:door",0,-open)
    

    There aren't any folder named"documents" in codea runtime neither xcode.
    Do I have to change all my sprite to this

    sprite("mypro:door",0,-open)
    

    and copy all my pics to a folder named mypro.spritepack?

  • SimeonSimeon Admin Mod
    Posts: 5,200

    You can, or you can put a "Documents.spritepack" into Xcode. Then you won't have to change your Lua code.

  • Posts: 52

    WOW! Excellent idea! Thanks a lot bro

  • edited August 2012 Posts: 489

    If you have not read it, I recommend the online manual for Lua version 5.0 and its advice on constructing new tables. A variation on @Simeon's advice would be:

    function setup()
        obj = {
            [0] = 456, -- If you really want the first obj to be 'obj[0]'
            9899,
            5453,
            54,
            3232,
            232,
            "hello",
            889
        }
        target = 1
    end
    
    function draw()
        print(obj[target]) -- But generally not a good idea to have 'print()' called
                           -- up to 60 times a second
    end
    
  • Posts: 52

    OK,I've already download it into my iPad.Thanks

Sign In or Register to comment.