Search for an item in a Lua list

后端 未结 10 2365
青春惊慌失措
青春惊慌失措 2020-11-29 00:56

If I have a list of items like this:

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

how do I check if \"orange\" is in this

相关标签:
10条回答
  • 2020-11-29 01:27

    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
    
    0 讨论(0)
  • 2020-11-29 01:30

    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
    
    0 讨论(0)
  • 2020-11-29 01:30

    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
    
    0 讨论(0)
  • 2020-11-29 01:32

    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

    0 讨论(0)
提交回复
热议问题