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

Checking If Variable Is In Table

Started by M4sh3dP0t4t03, 12 October 2013 - 07:11 AM
M4sh3dP0t4t03 #1
Posted 12 October 2013 - 09:11 AM
Is there a way in Lua to check if a table contains a variable without having to iterate through the whole table?
Engineer #2
Posted 12 October 2013 - 09:24 AM
If you mean to check for a value without iterating, no.
M4sh3dP0t4t03 #3
Posted 12 October 2013 - 09:33 AM
Ok, thanks! That is all what I needed to know!
Bomb Bloke #4
Posted 12 October 2013 - 09:58 AM
Well, that's not strictly true. It depends on how you're indexing things.

Eg, with strings you can do stuff like:

local myTable = {"yes"=true, "no"=true, "maybe"=true}

if myTable["yes"] then print("that string's in the table.") end
Engineer #5
Posted 12 October 2013 - 10:49 AM
Well, that's not strictly true. It depends on how you're indexing things.

Eg, with strings you can do stuff like:

local myTable = {"yes"=true, "no"=true, "maybe"=true}

if myTable["yes"] then print("that string's in the table.") end
That is the key, not the value
Bomb Bloke #6
Posted 12 October 2013 - 07:48 PM
Er, you may've narrowed down your definition of "value" a bit. In addition to having values assigned to them, keys are also named using values.

Whether you agree with my definition or not, it's still quite possible to confirm the existence of data in a table without the use of iteration.
Engineer #7
Posted 13 October 2013 - 03:22 AM
This is the basic structure of a table:

local t = {
  key1 = 'value1',
  key2 = 'value2'
}

And from what I understood from the OP, he is after those 'valueX' and not after the key. For a matter of fact, you can even have functions and tables as key, but you cannot call them without a pairs loop.
bobmandude9889 #8
Posted 13 October 2013 - 03:50 AM
You can do something like this


table = {
key1 = "value1",
key2 = "value2"
}

if table.key3 ~= null then
 print("exists")
else
 print("does not exist")
end
Edited on 13 October 2013 - 01:50 AM
Engineer #9
Posted 13 October 2013 - 05:02 AM
You can do something like this


table = {
key1 = "value1",
key2 = "value2"
}

if table.key3 ~= null then
print("exists")
else
print("does not exist")
end
First of all, null doesnt exist in lua. That is nil, and from my understanding, that is not what the OP is looking for.
Kingdaro #10
Posted 13 October 2013 - 11:51 AM
Technically, it's because "null" doesn't exist by default that its value is nil. :lol:/>
M4sh3dP0t4t03 #11
Posted 13 October 2013 - 03:16 PM
Just to clarify this, I meant checking for values and not keys.