Skip to content

Instantly share code, notes, and snippets.

@badforlabor
Created August 15, 2023 07:18
Show Gist options
  • Select an option

  • Save badforlabor/db6b9a1a6020b64950708ef0cf3736ea to your computer and use it in GitHub Desktop.

Select an option

Save badforlabor/db6b9a1a6020b64950708ef0cf3736ea to your computer and use it in GitHub Desktop.
local function test3_newindex2()
print("------- test3_newindex2 -------")
local t = {}
local _t_store = {}
local mt = {
__index = function (t, k)
print("*access to element " .. tostring(k))
return _t_store[k]
end,
__newindex = function(t, k, v)
print("Successfully set element \"" .. tostring(k) ..
"\" as " .. tostring(v))
--t[k] = v
rawset(t, k, v)
end
}
setmetatable(t, mt)
t[2] = "hello"
print(t[2])
t[2] = "hello2" -- 此时不会再次执行__newindex!因为t已经有2了
print(t[2])
end
local function test3_newindex1()
print("------- test3_newindex1 -------")
test3_newindex2()
local t = {}
local _t_store = {}
local mt = {
__index = function (t, k)
print("*access to element " .. tostring(k))
return _t_store[k]
end,
__newindex = function(t, k, v)
print("Successfully set element \"" .. tostring(k) ..
"\" as " .. tostring(v))
_t_store[k] = v
end
}
setmetatable(t, mt)
t[2] = "hello"
print(t[2])
t[2] = "hello2" -- 此时会再次执行__newindex,因为t中没有2,_t_store中才有2
print(t[2])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment