lua metatables中__newindex

reference:html

http://www.lua.org/manual/5.3/manual.htmlapp

 

__newindexThe 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.this

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 tablekey, 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.)lua

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.)spa

 

__newindex 用來對錶更新,__index 則用來對錶訪問。
code

metamethod 爲function

示例:orm

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)

執行結果:htm

nil	andrew
male	alex

metamethod 爲table

示例1:get

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)

執行結果:it

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
相關文章
相關標籤/搜索