如何通过其键删除lua表条目? [英] How to remove a lua table entry by its key?

查看:55
本文介绍了如何通过其键删除lua表条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个lua表,可以用作哈希图,即带有字符串键:

I have a lua table that I use as a hashmap, ie with string keys :

local map = { foo = 1, bar = 2 }

我想弹出"该表的键所标识的元素.有一个 table.remove()方法,但是它只删除要删除的元素的索引(即一个数字),而不是一个通用键.我希望能够执行 table.remove(map,'foo'),这是我实现它的方式:

I would like to "pop" an element of this table identified by its key. There is a table.remove() method, but it only takes the index of the element to remove (ie a number) and not a generic key. I would like to be able to do table.remove(map, 'foo') and here is how I implemented it :

function table.removekey(table, key)
    local element = table[key]
    table[key] = nil
    return element
end

有更好的方法吗?

推荐答案

否,将键的值设置为 nil 是删除表的哈希映射部分中的项的公认方法.您正在做的是标准的.但是,我建议您不要覆盖 table.remove()-对于表的数组部分,默认的table.remove()功能包括对索引重新编号,而您的覆盖不会这样做.如果您确实想将函数添加到 table 函数集中,那么我可能会将其命名为 table.removekey()之类的东西.

No, setting the key's value to nil is the accepted way of removing an item in the hashmap portion of a table. What you're doing is standard. However, I'd recommend not overriding table.remove() - for the array portion of a table, the default table.remove() functionality includes renumbering the indices, which your override would not do. If you do want to add your function to the table function set, then I'd probably name it something like table.removekey() or some such.

这篇关于如何通过其键删除lua表条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆