问题
I am writing a lua program that has a table which is a member of another table. When I add a new date to that member table everything is ok. But when I want to search in that table no matter what key I give I always get the last row added to the table. How do I search properly in that member table?
Stream = {name = ""}
function Stream:new(obj, name)
obj = obj or {}
setmetatable(obj, self)
self.__index = self
self.name = name or "default"
--[[ declaration and initialization of another table memebers--]]
return obj
end
Table = {streams = {}}
function Table:new(obj)
obj = obj or {}
setmetatable(obj, self)
self.__index = self
self.streams = {}
--[[ declaration and initialization of another table memebers--]]
return obj
end
table_ = Table:new(nil)
table_.streams["stdout"] = Stream:new(nil,"stdout")
table_.streams["stderr"] = Stream:new(nil,"stderr")
print("Stdout stream name:", table_.streams["stdout"].name)
print("Stream table content:")
for k, v in pairs(table_.streams) do
print(k, v)
end
I expect the output to be:
Stdout stream name: stdout
But I get:
Stdout stream name: stderr
回答1:
I think you are misunderstanding what you should put in obj
and what you should put in self
in your :new
functions. What you put in self ends up being shared between all objects you create via your :new
function. You may want to look for more info on metatables. Here is small example to demonstrate
local t = {}
function t:new(name)
local obj = {
Name = name
}
setmetatable(obj, self)
self.__index = self
self.SharedName = name
return obj
end
local o1 = t:new("a")
print(o1.Name) -- a
print(o1.SharedName) -- a
local o2 = t:new("b")
print(o1.Name) -- a
print(o1.SharedName) -- b
-- after creating second object SharedName field was overwritten like in your case
print(o2.Name) -- b
print(o2.SharedName) -- b
来源:https://stackoverflow.com/questions/56111919/how-to-search-in-table-member-of-another-table-in-lua