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

后端 未结 5 783
失恋的感觉
失恋的感觉 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 09:01

    There's another way you can do it, using metamethods. [Edited to allow you to remove values too]

    t = {} -- Create your table, can be called anything
    t.r_index = {} -- Holds the number value, i.e. t[1] = 'Foo'
    t.r_table = {} -- Holds the string value, i.e. t['Foo'] = 1
    
    mt = {} -- Create the metatable
    mt.__newindex = function (self, key, value) -- For creating the new indexes
        if value == nil then -- If you're trying to delete an entry then
            if tonumber(key) then -- Check if you are giving a numerical index
                local i_value = self.r_index[key] -- get the corrosponding string index
                self.r_index[key] = nil -- Delete
                self.r_table[i_value] = nil
            else -- Otherwise do the same as above, but for a given string index
                local t_value = self.r_table[key]
                self.r_index[t_value] = nil
                self.r_table[key] = nil
            end
        else
            table.insert(self.r_index, tonumber(key), value) -- For t[1] = 'Foo'
            self.r_table[value] = key -- For t['Foo'] = 1
        end
    end
    mt.__index = function (self, key) -- Gives you the values back when you index them
        if tonumber(key) then
            return (self.r_index[key]) -- For For t[1] = 'Foo'
        else
            return (self.r_table[key]) -- For t['Foo'] = 1
        end
    end
    
    setmetatable(t, mt) -- Creates the metatable
    
    t[1] = "Rock1" -- Set the values
    t[2] = "Rock2"
    
    print(t[1], t[2]) -- And *should* proove that it works
    print(t['Rock1'], t['Rock2'])
    
    t[1] = nil
    print(t[1], t[2]) -- And *should* proove that it works
    print(t['Rock1'], t['Rock2'])
    

    It's more versatile as you can copy the t value and take it with you; it also means that you only have to play around with the one variable most of the time - hopefully should reduce the likelihood of you trying to access the wrong thing.

提交回复
热议问题