reference:
http://www.lua.org/manual/5.3/manual.html
__newindex
: The indexing assignment table[key] = value
. Like the index event, this event happens when table
is not a table or when key
is not present in table
. The metamethod is looked up in table
.
Like with indexing, the metamethod for this event can be either a function or a table. If it is a function, it is called with table
, key
, and value
as arguments. If it is a table, Lua does an indexing assignment to this table with the same key and value. (This assignment is regular, not raw, and therefore can trigger another metamethod.)
Whenever there is a __newindex
metamethod, Lua does not perform the primitive assignment. (If necessary, the metamethod itself can call rawset
to do the assignment.)
__newindex 用来对表更新,__index 则用来对表访问。
metamethod 为function
示例:
student = {}
student_info = {["name"] ="andrew"}
student_info.__newindex = function(t, key, value)
rawset(t,key,value)
end
student = setmetatable({},student_info)
student.gender = "male"
student.name = "alex"
print(student_info.gender, student_info.name)
print(student.gender,student.name)
执行结果:
nil andrew
male alex
metamethod 为table
示例1:
student_info = {["name"] ="andrew"}
student = setmetatable({},{__newindex=student_info})
student.gender = "male"
student.name = "alex"
print(student_info.gender, student_info.name)
print(student.gender,student.name)
执行结果:
male alex
nil nil
示例2:
student = {"hello"}
student_info = {["name"] ="andrew"}
student = setmetatable(student,{__newindex=student_info}) --line 3
--student = setmetatable({},{__newindex=student_info})
student.gender = "male"
student.name = "alex"
print(student_info.gender, student_info.name,student_info[1])
print(student.gender,student.name, student[1])
执行结果:
male alex nil
nil nil hello
示例3:
student = {"hello"}
student_info = {["name"] ="andrew"}
--student = setmetatable(student,{__newindex=student_info})
student = setmetatable({},{__newindex=student_info}) --line 4
student.gender = "male"
student.name = "alex"
print(student_info.gender, student_info.name,student_info[1])
print(student.gender,student.name, student[1])
执行结果:
male alex nil
nil nil nil