In Lua, how do you find out the key an object is stored in?

后端 未结 5 781
失恋的感觉
失恋的感觉 2020-12-21 07:59

How would you print() out or find out the index of an object?

For example, if I spawned 20 random rock objects on screen into an array RockTable = {};<

5条回答
  •  借酒劲吻你
    2020-12-21 08:54

    The simplest way is to add an "index" property to each rock:

    RockTable = {}
    
    for i=1,20 do
    
        local rock
        -- do your thing that generates a new 'rock' object
    
        rock.index = #RockTable + 1
        RockTable[rock.index] = rock
    
    end
    

    If you use a touch listener method, you can retrieve the rock this way:

    function touchListener( event )
        local rock = event.target
        local rockIndex = rock.index
        -- ...
    end
    

    It is true that you can maintain a second table with indices, but I find my method cleaner - when it is time to remove things, you only have to worry about one table, the main one.

    I have a question though: why do you need to retrieve that index? In most cases, well designed event listener functions are enough, you don't need to "find" your objects. Of course I lack information on what you are trying to do, but it is possible that you are over-complicating things.

提交回复
热议问题