在 Lua 列表中搜索项目

发布于 2024-07-15 09:38:57 字数 239 浏览 7 评论 0原文

如果我有一个这样的项目列表:

local items = { "apple", "orange", "pear", "banana" }

如何检查“橙色”是否在此列表中?

在Python中我可以这样做:

if "orange" in items:
    # do something

Lua中有等价的吗?

If I have a list of items like this:

local items = { "apple", "orange", "pear", "banana" }

how do I check if "orange" is in this list?

In Python I could do:

if "orange" in items:
    # do something

Is there an equivalent in Lua?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

无可置疑 2024-07-22 09:38:57

您可以使用 Programming in Lua 中的类似集合:

function Set (list)
  local set = {}
  for _, l in ipairs(list) do set[l] = true end
  return set
end

然后您可以将列表放入设置并测试成员资格:

local items = Set { "apple", "orange", "pear", "banana" }

if items["orange"] then
  -- do something
end

或者您可以直接迭代列表:

local items = { "apple", "orange", "pear", "banana" }

for _,v in pairs(items) do
  if v == "orange" then
    -- do something
    break
  end
end

You could use something like a set from Programming in Lua:

function Set (list)
  local set = {}
  for _, l in ipairs(list) do set[l] = true end
  return set
end

Then you could put your list in the Set and test for membership:

local items = Set { "apple", "orange", "pear", "banana" }

if items["orange"] then
  -- do something
end

Or you could iterate over the list directly:

local items = { "apple", "orange", "pear", "banana" }

for _,v in pairs(items) do
  if v == "orange" then
    -- do something
    break
  end
end
划一舟意中人 2024-07-22 09:38:57

请改用以下表示形式:

local items = { apple=true, orange=true, pear=true, banana=true }
if items.apple then
    ...
end

Use the following representation instead:

local items = { apple=true, orange=true, pear=true, banana=true }
if items.apple then
    ...
end
捶死心动 2024-07-22 09:38:57

您将亲眼目睹 Lua 只有一种数据结构的缺点之一——您必须推出自己的数据结构。 如果您坚持使用 Lua,您将逐渐积累一个以您喜欢的方式操作表格的函数库。 我的库包括列表到集合的转换和高阶列表搜索功能:

function table.set(t) -- set of list
  local u = { }
  for _, v in ipairs(t) do u[v] = true end
  return u
end

function table.find(f, l) -- find element v of l satisfying f(v)
  for _, v in ipairs(l) do
    if f(v) then
      return v
    end
  end
  return nil
end

You're seeing firsthand one of the cons of Lua having only one data structure---you have to roll your own. If you stick with Lua you will gradually accumulate a library of functions that manipulate tables in the way you like to do things. My library includes a list-to-set conversion and a higher-order list-searching function:

function table.set(t) -- set of list
  local u = { }
  for _, v in ipairs(t) do u[v] = true end
  return u
end

function table.find(f, l) -- find element v of l satisfying f(v)
  for _, v in ipairs(l) do
    if f(v) then
      return v
    end
  end
  return nil
end
回忆躺在深渊里 2024-07-22 09:38:57

你想怎么写就怎么写,但是直接在列表上迭代比生成pairs()或ipairs()要快

#! /usr/bin/env lua

local items = { 'apple', 'orange', 'pear', 'banana' }

local function locate( table, value )
    for i = 1, #table do
        if table[i] == value then print( value ..' found' ) return true end
    end
    print( value ..' not found' ) return false
end

locate( items, 'orange' )
locate( items, 'car' )

找不到车

Write it however you want, but it's faster to iterate directly over the list, than to generate pairs() or ipairs()

#! /usr/bin/env lua

local items = { 'apple', 'orange', 'pear', 'banana' }

local function locate( table, value )
    for i = 1, #table do
        if table[i] == value then print( value ..' found' ) return true end
    end
    print( value ..' not found' ) return false
end

locate( items, 'orange' )
locate( items, 'car' )

orange found
car not found

白芷 2024-07-22 09:38:57

Lua 表更类似于 Python 字典而不是列表。 您创建的表本质上是一个从 1 开始的索引字符串数组。 使用任何标准搜索算法来查找某个值是否在数组中。 另一种方法是将值存储为表键,而不是如 Jon Ericson 帖子的 set 实现中所示。

Lua tables are more closely analogs of Python dictionaries rather than lists. The table you have create is essentially a 1-based indexed array of strings. Use any standard search algorithm to find out if a value is in the array. Another approach would be to store the values as table keys instead as shown in the set implementation of Jon Ericson's post.

何处潇湘 2024-07-22 09:38:57

这是一个 swiss-armyknife 函数,您可以使用它:

function table.find(t, val, recursive, metatables, keys, returnBool)
    if (type(t) ~= "table") then
        return nil
    end

    local checked = {}
    local _findInTable
    local _checkValue
    _checkValue = function(v)
        if (not checked[v]) then
            if (v == val) then
                return v
            end
            if (recursive and type(v) == "table") then
                local r = _findInTable(v)
                if (r ~= nil) then
                    return r
                end
            end
            if (metatables) then
                local r = _checkValue(getmetatable(v))
                if (r ~= nil) then
                    return r
                end
            end
            checked[v] = true
        end
        return nil
    end
    _findInTable = function(t)
        for k,v in pairs(t) do
            local r = _checkValue(t, v)
            if (r ~= nil) then
                return r
            end
            if (keys) then
                r = _checkValue(t, k)
                if (r ~= nil) then
                    return r
                end
            end
        end
        return nil
    end

    local r = _findInTable(t)
    if (returnBool) then
        return r ~= nil
    end
    return r
end

您可以使用它来检查值是否存在:

local myFruit = "apple"
if (table.find({"apple", "pear", "berry"}, myFruit)) then
    print(table.find({"apple", "pear", "berry"}, myFruit)) -- 1

您可以使用它来查找密钥:

local fruits = {
    apple = {color="red"},
    pear = {color="green"},
}
local myFruit = fruits.apple
local fruitName = table.find(fruits, myFruit)
print(fruitName) -- "apple"

我希望 recursive 参数不言自明。

metatables 参数还允许您搜索元表。

keys 参数使函数在列表中查找键。 当然,这在 Lua 中是没有用的(你可以只做fruits[key]),但是与recursivemetatables一起使用,它变得很方便。

当您的表中的键为 false 时,returnBool 参数是一个安全保障(是的,这是可能的:fruits = {false="苹果”})

This is a swiss-armyknife function you can use:

function table.find(t, val, recursive, metatables, keys, returnBool)
    if (type(t) ~= "table") then
        return nil
    end

    local checked = {}
    local _findInTable
    local _checkValue
    _checkValue = function(v)
        if (not checked[v]) then
            if (v == val) then
                return v
            end
            if (recursive and type(v) == "table") then
                local r = _findInTable(v)
                if (r ~= nil) then
                    return r
                end
            end
            if (metatables) then
                local r = _checkValue(getmetatable(v))
                if (r ~= nil) then
                    return r
                end
            end
            checked[v] = true
        end
        return nil
    end
    _findInTable = function(t)
        for k,v in pairs(t) do
            local r = _checkValue(t, v)
            if (r ~= nil) then
                return r
            end
            if (keys) then
                r = _checkValue(t, k)
                if (r ~= nil) then
                    return r
                end
            end
        end
        return nil
    end

    local r = _findInTable(t)
    if (returnBool) then
        return r ~= nil
    end
    return r
end

You can use it to check if a value exists:

local myFruit = "apple"
if (table.find({"apple", "pear", "berry"}, myFruit)) then
    print(table.find({"apple", "pear", "berry"}, myFruit)) -- 1

You can use it to find the key:

local fruits = {
    apple = {color="red"},
    pear = {color="green"},
}
local myFruit = fruits.apple
local fruitName = table.find(fruits, myFruit)
print(fruitName) -- "apple"

I hope the recursive parameter speaks for itself.

The metatables parameter allows you to search metatables as well.

The keys parameter makes the function look for keys in the list. Of course that would be useless in Lua (you can just do fruits[key]) but together with recursive and metatables, it becomes handy.

The returnBool parameter is a safe-guard for when you have tables that have false as a key in a table (Yes that's possible: fruits = {false="apple"})

蘸点软妹酱 2024-07-22 09:38:57
function valid(data, array)
 local valid = {}
 for i = 1, #array do
  valid[array[i]] = true
 end
 if valid[data] then
  return false
 else
  return true
 end
end

这是我用来检查数据是否在数组中的函数。

function valid(data, array)
 local valid = {}
 for i = 1, #array do
  valid[array[i]] = true
 end
 if valid[data] then
  return false
 else
  return true
 end
end

Here's the function I use for checking if data is in an array.

浊酒尽余欢 2024-07-22 09:38:57

使用元表的解决方案......

local function preparetable(t)
 setmetatable(t,{__newindex=function(self,k,v) rawset(self,v,true) end})
end

local workingtable={}
preparetable(workingtable)
table.insert(workingtable,123)
table.insert(workingtable,456)

if workingtable[456] then
...
end

Sort of solution using metatable...

local function preparetable(t)
 setmetatable(t,{__newindex=function(self,k,v) rawset(self,v,true) end})
end

local workingtable={}
preparetable(workingtable)
table.insert(workingtable,123)
table.insert(workingtable,456)

if workingtable[456] then
...
end
酷到爆炸 2024-07-22 09:38:57

可以使用以下表示:

local items = {
    ["apple"]=true, ["orange"]=true, ["pear"]=true, ["banana"]=true
}

if items["apple"] then print("apple is a true value.") end
if not items["red"] then print("red is a false value.") end

相关输出:

apple is a true value.
red is a false value.

您还可以使用以下代码来检查布尔有效性:

local items = {
    ["apple"]=true, ["orange"]=true, ["pear"]=true, ["banana"]=true,
    ["red"]=false, ["blue"]=false, ["green"]=false
}

if items["yellow"] == nil then print("yellow is an inappropriate value.") end
if items["apple"] then print("apple is a true value.") end
if not items["red"] then print("red is a false value.") end

输出为:

yellow is an inappropriate value.
apple is a true value.
red is a false value.

检查 表格教程了解更多信息。

The following representation can be used:

local items = {
    ["apple"]=true, ["orange"]=true, ["pear"]=true, ["banana"]=true
}

if items["apple"] then print("apple is a true value.") end
if not items["red"] then print("red is a false value.") end

Related output:

apple is a true value.
red is a false value.

You can also use the following code to check boolean validity:

local items = {
    ["apple"]=true, ["orange"]=true, ["pear"]=true, ["banana"]=true,
    ["red"]=false, ["blue"]=false, ["green"]=false
}

if items["yellow"] == nil then print("yellow is an inappropriate value.") end
if items["apple"] then print("apple is a true value.") end
if not items["red"] then print("red is a false value.") end

The output is:

yellow is an inappropriate value.
apple is a true value.
red is a false value.

Check Tables Tutorial for additional information.

他夏了夏天 2024-07-22 09:38:57
function table.find(t,value)
    if t and type(t)=="table" and value then
        for _, v in ipairs (t) do
            if v == value then
                return true;
            end
        end
        return false;
    end
    return false;
end
function table.find(t,value)
    if t and type(t)=="table" and value then
        for _, v in ipairs (t) do
            if v == value then
                return true;
            end
        end
        return false;
    end
    return false;
end
丶情人眼里出诗心の 2024-07-22 09:38:57

您可以使用此解决方案:

items = { 'a', 'b' }
for k,v in pairs(items) do 
 if v == 'a' then 
  --do something
 else 
  --do something
 end
end

items = {'a', 'b'}
for k,v in pairs(items) do 
  while v do
    if v == 'a' then 
      return found
    else 
      break
    end
  end 
 end 
return nothing

you can use this solution:

items = { 'a', 'b' }
for k,v in pairs(items) do 
 if v == 'a' then 
  --do something
 else 
  --do something
 end
end

or

items = {'a', 'b'}
for k,v in pairs(items) do 
  while v do
    if v == 'a' then 
      return found
    else 
      break
    end
  end 
 end 
return nothing
纸伞微斜 2024-07-22 09:38:57

可以使用一个简单的函数:

  • 返回 nil,如果在表中找不到该项目,则
  • 返回该项目的索引,如果在表中找到该项目,
local items = { "apple", "orange", "pear", "banana" }

local function search_value (tbl, val)
    for i = 1, #tbl do
        if tbl[i] == val then
            return i
        end
    end
    return nil
end

print(search_value(items, "pear"))
print(search_value(items, "cherry"))

上述代码的输出将是

3
nil

A simple function can be used that :

  • returns nil, if the item is not found in table
  • returns index of item, if item is found in table
local items = { "apple", "orange", "pear", "banana" }

local function search_value (tbl, val)
    for i = 1, #tbl do
        if tbl[i] == val then
            return i
        end
    end
    return nil
end

print(search_value(items, "pear"))
print(search_value(items, "cherry"))

output of above code would be

3
nil
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文