问题描述
我正在编写一个lua程序,该程序具有一个表,该表是另一个表的成员.当我向该成员表添加新日期时,一切正常.但是,当我想在该表中进行搜索时,无论我给出什么键,我总会得到添加到表中的最后一行.如何在该成员表中正确搜索?
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
我希望输出为:Stdout stream name: stdout
但是我得到:Stdout stream name: stderr
推荐答案
我认为您误解了应该将obj
中的内容以及应该将self
中的内容放入:new
函数中的情况.自己输入的内容最终会在通过:new
函数创建的所有对象之间共享.您可能需要查找有关元表的更多信息.这是一个演示
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
这篇关于如何在Lua中的另一个表的表成员中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!