This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Kryptic's profile picture

If function with elements of a table

Started by Kryptic, 06 January 2013 - 09:49 AM
Kryptic #1
Posted 06 January 2013 - 10:49 AM
[left]Hi, I'm pretty new to Lua but thanks to the vast wealth of tutorials available on the net, I'm learning fairly fast.

However I've currently got a problem, and this time google hasn't provided me with any answers, so hopefully someone here will be able to help.

I understand how to solve my problem from a maths point of view so hopefully the coding will be similar.

I have two variables: x and y, and a set/table z, where z={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16} and x∈z.

I want to create an 'if' function along the lines of:

If y∈{{z}\x}, then …

In other words, if y equals any element of the table/set z, excluding x, then the condition is true, otherwise it is false.

An ideas how to translate this into Lua code?

Thanks.[/left]
Kingdaro #2
Posted 06 January 2013 - 11:19 AM
You'd probably have to check every element of the table. I personally find that using variable names actually representative of what they are makes them less confusing, so I'll just go ahead and do that.

Here's a "contains" function.


function contains(set, element, condition)
  for i=1, #set do
    if element == set[i] and (condition == nil or condition(set[i])) then
      return i
    end
  end
end

It basically goes though the table and sees if it can find said element in the table, then returns where it found it. Example usage:


local set = {1,2,3,'a','b','c'}
if contains(set, 'a') then
  print 'stuff'
end

This will print "stuff", because 'a' is found at position 4 in the table "set".
ChunLing #3
Posted 06 January 2013 - 11:33 AM
I would go ahead and build the table in reverse, with the values as indexes, so:
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
becomes:
{[1]=true,[2]=true,[3]=true,[4]=true,[5]=true,[6]=true,[7]=true,[8]=true,[9]=true,[10]=true,[11]=true,[12]=true,[13]=true,[14]=true,[15]=true,[16]=true}
Then you just check if something is an index in the table. If you want to return the position, then you have the table store the indexes instead of just true. Unfortunately the above table can't be used to illustrate this very well cause the original has the values equal to their indexes.
Edited on 06 January 2013 - 10:35 AM
Kryptic #4
Posted 07 January 2013 - 11:47 AM
Thanks for the help guys! Much appreciated.