How to know if a certain value is within a specific table

Asked

Viewed 125 times

2

I want to identify if a name is inside a list.

lista = {"name","name2","name3"}

*In python I could do if name in lista:, but in moon It’s another way, which I don’t know.

2 answers

3

Can make a function to iterate:

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

And wear it like this

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

if items["orange"] then
  -- faz algo
end

Or, iterate straight into the list

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

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

Original: https://stackoverflow.com/a/656232/916193

Alternative, by indexing by names:

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

Original: https://stackoverflow.com/a/656257/916193

  • I’m trying to develop this: Create a small module that aims to reproduce the powers of the game’s staff positions. Moderator - ! Player ban to appear a black textarea on your screen and also kill it on all maps. ! unban Player to undo the ban (effects of the !ban command) Mapcrew - ! np map to place a map. Extra point for anyone who makes a ! Npp map (the current map will not be skipped) and ! ch Player (assign Shaman in next round) Funcorp - ! color Player to change color of player nickname.

  • 1

    Cool, hope it gets good! It’s for RPG?

0

If the object in question is an array and contains only primitive values, then the recommended function is:

local function pertence(nome, array)
    for _, valor in ipairs(array) do
        if nome == valor then return true end
    end

    return false
end

-- teste
local a = { 1, 2, 4, 8, 16, 32, 64, 128}
local b = { 'Ana', 'Bia', 'Carla', 'Damares'}

local inner = {1, 2}
local c = { inner, {3, 4}, {5, 6} }

print(pertence(9, a)) -- false
print(pertence(32, a)) -- true
print(pertence('Elena', b)) -- false
print(pertence('Bia', b)) -- true

-- cuidado!
print(pertence({1, 2}, c)) -- false
print(pertence(inner, c)) -- true

Note that the iterator ipairs just sweep the table from 1 to its size. If there are non-integer keys, or numerical keys smaller than 1, or even holes in the table, this method does not work and must be used pairs.

In addition, equality nome == valor can bring undesirable results, if you have tables inside the table, because the comparison is by reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.