Determine whether x belongs to y array

Posted by Gpan on Tue 12 Jan 2021 05:10 AM — 2 posts, 12,480 views.

#0
x = apple Y = {apple|pear} Z={sword|blade}

if X belongs to Y, then return Y

one function like this: if Y[X] then return Y.

i wanna know is there a packaged func can do the same thing
USA Global Moderator #1
Set X and Y like this:

X = "apple"
Y = {
 ["apple"]=true,
 ["pear"]=true,
}


Then Y[X] will be true if X is a key in Y and nil if not.

Then you can use something like
(Y[X] and Y)


That will equal Y if X is in Y, otherwise it will equal nil.

Or if you want it in function form, what you had is almost complete:


X = "apple"
Y = {
 ["apple"]=true,
 ["pear"]=true,
}

function a_if_b_in_a(a, b)
   if a[b] then return a end
end

result = a_if_b_in_a(Y, X)
same_result = (Y[X] and Y)