This is a read-only snapshot of the ComputerCraft forums,
taken in April 2020.
Checking If Variable Is In Table
Started by M4sh3dP0t4t03, 12 October 2013 - 07:11 AMPosted 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?
Posted 12 October 2013 - 09:24 AM
If you mean to check for a value without iterating, no.
Posted 12 October 2013 - 09:33 AM
Ok, thanks! That is all what I needed to know!
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:
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
Posted 12 October 2013 - 10:49 AM
That is the key, not the valueWell, 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
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.
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.
Posted 13 October 2013 - 03:22 AM
This is the basic structure of a table:
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.
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.
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
Posted 13 October 2013 - 05:02 AM
First of all, null doesnt exist in lua. That is nil, and from my understanding, that is not what the OP is looking for.You can do something like thistable = { key1 = "value1", key2 = "value2" } if table.key3 ~= null then print("exists") else print("does not exist") end
Posted 13 October 2013 - 11:51 AM
Technically, it's because "null" doesn't exist by default that its value is nil. :lol:/>
Posted 13 October 2013 - 03:16 PM
Just to clarify this, I meant checking for values and not keys.