lua - 有没有办法知道是否在lua中的数组中添加或删除了一个键?
问题描述
local t = {}
local mt = setmetatable({
-- some meta method to know when a key is added or lost and prints a message
}, t)
有没有办法做到这一点。我和某人讨论过这个问题,他们说我不能只使用元方法,还可以使用代理。我对如何使这项工作有些困惑。任何人都可以帮忙吗?
谢谢
解决方案
要在 lua 中跟踪表键,metatable 中有 2 个最重要的键:__index
和__newindex
.
__newindex
如果找不到这样的键,则用于在表中创建新键。__index
如果表中没有这样的键,则用于获取值。
可以跟踪创建,但不能跟踪分配,因此__newindex
无法跟踪密钥删除:
<script src="https://github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js"></script>
<script type="application/lua">
local t={}
setmetatable(t, {
__newindex = function(self, key, value)
print('Added Key:'..key,'Value:'..value)
rawset(self, key, value)
end
})
t.test = 'test'
t.test = nil -- delete not tracked
t.test = 'test2'
</script>
使用代理表__newindex
,__index
我们可以跟踪每个分配:
<script src="https://github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js"></script>
<script type="application/lua">
local t={}
local proxytable={}
setmetatable(t, {
__newindex = function(self, key, value)
if proxytable[key] then
if value == nil then
print('Deleted Key:'..key)
else
print('Changed Key:'..key,'Value:'..value)
end
else
print('Added Key:'..key,'Value:'..value)
end
rawset(proxytable, key, value)
end,
__index = proxytable
})
t.test = 'test'
t.test = nil
t.test = 'test2'
t.test = 'test3'
t.test = nil
</script>
如果你想用 , 枚举表键pairs()
,ipairs()
那么你需要使用元键__pairs
,__ipairs
因为原始表总是空的。
推荐阅读
- go - 解决非主包中的相对路径的问题
- asp.net-core - 剃刀中的锚标记助手
- java - 如何正确地将字符串与时间从文本文件转换为时间?
- javascript - jQuery addClass page A, and next page B history back() 保持addClass A
- google-sheets - Merge Irregular Time Based Data Series
- python - 为什么 ActionChains 拖放 (Selenium WD) 不能与此脚本一起使用?
- spring-boot - sping boot - how to configure application class in a different package, and controllers and services in other package
- javascript - DOM multiple IDs with the same function
- python - Remore rows from pandas dataframe with logics based on multiple column
- android - 无法解析 Firebase 符号