Lua Table - 搜索以字母开头的项目

Lua Table - Search for Items that starts with an Letter

我有这个table

    animals = {
     {sname = "bunny", name = "bunny hase", size = 4, size2 = 8, size3 = 9},
     {sname = "mouse", name = "Micky Mouse", size = 1, size2 = 12, size3 = 22},
     {sname = "cow", name = "Die Kuh", size = 30, size2 = 33, size3 = 324
}

我可以通过列出的条目进行搜索

for _,v in pairs(animals) do
  if v.sname == "bunny" then
    print(v.sname, v.name, v.size, v.size2, v.size3)
    break
  end
end

并得到结果:

bunny   bunny hase  4   8   9

现在我想在我的 table 中搜索,以单个字母开头,例如“b”,这会显示所有以字母“b”开头的条目以获得相同的结果?

我没有找到解决方案。你能帮帮我吗?

首先:table animals 需要尾随 } ;-)

将其放入 Lua -i 控制台并使用...

>animals = {                                   
     {sname = "bunny", name = "bunny hase", size = 4, size2 = 8, size3 = 9},
     {sname = "mouse", name = "Micky Mouse", size = 1, size2 = 12, size3 = 22},
     {sname = "cow", name = "Die Kuh", size = 30, size2 = 33, size3 = 324}
}
-- Now set a __call metamethod on same table
>setmetatable(animals,{__call=function(tab,...)
local args={...}
for key, value in pairs(tab) do
if value.sname:find(args[1],1) then print(key,'=',value.sname) end
end
end})
table: 0x565c4a00
-- Lets try it once
>animals('b')                                  
1    =    bunny
-- Next one
>animals('c')
3    =    cow
-- Last one
>animals('m')
2    =    mouse

使用元tables 将你的东西放在一起。
另一个很好的地方是 __index 元方法,它可以包含你需要的所有函数 table 并且可以像字符串上的字符串函数一样使用。
(喜欢:value.sname:find(args[1],1)
这导致了 find 应该做什么的核心。
在第一个示例中,它在整个 sname 中查找匹配模式。
检查 Lua 模式也很有用。
也许 ^ 只在开头听起来很聪明?
因此构建查找模式:'^'..args[1]
...如果您的动物中有牛、乌鸦、青蛙和鱼,请使用多个字母。

__index

中函数名称为 find 的示例
>animals = {                                   
     {sname = "bunny", name = "bunny hase", size = 4, size2 = 8, size3 = 9},
     {sname = "mouse", name = "Micky Mouse", size = 1, size2 = 12, size3 = 22},
     {sname = "cow", name = "Die Kuh", size = 30, size2 = 33, size3 = 324}
}
-- Place a find function into __index
>setmetatable(animals,{__index={find=function(tab,...)
local args={...}
for key, value in pairs(tab) do
if value.sname:find('^'..args[1]) then print(key,'=',value.sname) end
end
end}})
table: 0x565c3db0
-- first
>animals:find('c')                                
3       =       cow
-- next
>animals:find('m')
2       =       mouse
-- last
>animals:find('b')
1       =       bunny

如果您想打印所有键值,请扩展 find() 中的 print()

停止,我发现了一个问题....

看这里 - 我更喜欢第一个解决方案:

animals = {                                   
     {sname = "bunny", name = "bunny hase", size = 4, size2 = 8, size3 = 9},
     {sname = "mouse", name = "Micky Mouse", size = 1, size2 = 12, size3 = 22},
     {sname = "cow", name = "Die Kuh", size = 30, size2 = 33, size3 = 324}
}
-- Now set a __call metamethod on same table
setmetatable(animals,{__call=function(tab,...)
local args={...}
for v,k in pairs(tab) do
if k.sname:find(args[1],1) then print(v,'=',k.sname) end
end
end})


-- Search Entries with Start U.....
-- there should be no result, but....
animals('u')

我得到结果: 1 = 兔子 2 = 鼠标

不应该是这样的结果!