获取表项索引
我无法获取表条目索引。我需要它从表中删除一个项目。
我使用 table.insert
将条目添加到表中。
另一个问题:为什么 Lua 没有“重载”函数 table.remove 以便可以通过关联索引删除项目?
I can't get table entry index. I need it to remove an item from table.
I use table.insert
to add entries to table.
Another question: why Lua doesn't have "overload" to function table.remove so one can remove item by associative index?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
表在键和值之间实现无序的一对多关系。换句话说,任何特定的键(索引)在表中只能出现一次,但一个值可以出现多次。
如果您知道键
k
,则t[k] = nil
将从表中删除该键和关联值。但是,此操作不会影响表中的任何其他键或值。table.insert
和table.remove
函数对从 1 开始的顺序整数键集进行操作,按照惯例使用这些键来实现数组或列表。为此,他们操纵列表中的其他值,以防止列表出现漏洞。查找某个值所在的键的一种方法是简单地搜索表。如果要多次执行此操作,那么构建第二个表来反转键/值对可能是个好主意,以便按值查找与按索引查找一样快。
合适的实施将取决于您的假设和需求。一些样本是:
Tables implement an unordered one to many relation between keys and values. In other words, any particular key (index) can only appear once in a table, but a value can appear multiple times.
If you know the key
k
, thent[k] = nil
will remove both the key and the associated value from the table. However, this operation has no effect on any other keys or values in the table.The
table.insert
andtable.remove
functions operate over the set of sequential integer keys beginning at 1, that are used by convention to implement arrays or lists. For that purpose, they manipulate other values in the list so as to keep the list from developing holes.One way to find a key at which some value is found is to simply search the table. If this will be done more than once, then it is probably a good idea to build a second table that inverts the key/value pairs so that lookup by value is as fast as lookup by index.
A suitable implementation will depend on your assumptions and needs. Some samples are:
t[k]=nil
从t
中删除带有键k
的条目。对于第二个问题,答案是表可以有单独的元表。
t[k]=nil
removes fromt
the entry with keyk
.For the second question, the answer is that tables can have individual metatables.