Check if the array contains a specific value

I have this array with some values ​​(int), and I want to check if the value set by the user is equal to the value in this line. If so, display a message like "Got your string."

List example:

local op = { {19}, {18}, {17} } if 13 == (the values from that array) then message else other message 

How can I do that?

+7
lua-table lua
source share
3 answers

Lua does not have strict arrays like other languages ​​- it only has hash tables. Tables in Lua are considered massive when their indexes are numerically and densely packed without leaving spaces. The indices in the following table will be 1, 2, 3, 4 .

 local t = {'a', 'b', 'c', 'd'} 

When you have an array similar to a table, you can check to see if it contains a specific value by going through the table. You can use the for..in and ipairs to create a generic function.

 local function has_value (tab, val) for index, value in ipairs(tab) do if value == val then return true end end return false end 

We can use the if condition above to get our result.

 if has_value(arr, 'b') then print 'Yep' else print 'Nope' end 

To repeat my comment above, your current sample code is not a table of numbers like an array. Instead, it is a massive table containing table tables that have numbers in each of their first indexes. You will need to change the function above to work with your displayed code, making it less general.

 local function has_value (tab, val) for index, value in ipairs(tab) do -- We grab the first index of our sub-table instead if value[1] == val then return true end end return false end 

Lua is not a very large or complex language, and its syntax is very clear. If the above concepts are completely alien to you, you need to spend some time reading real literature, and not just copying examples. I would advise reading Lua Programming to make sure you understand the basics. This is the first edition intended for Lua 5.1.

+14
source share

You can also check if a value in your array exists more efficiently by moving your values ​​to the index and assigning them a true value.

Then, when you check your table, you just check if a value exists in this index, which will save you some time because you do not have to go through the whole table in the worst case ...

Here is an example that I had in mind:

 local op = { [19]=true, [18]=true, [17]=true } if op[19] == true then print("message") else print("other message") end 
+6
source share

The op table of your question is an array (table) of arrays.

To check if a value exists in a table:

 local function contains(table, val) for i=1,#table do if table[i] == val then return true end end return false end local table = {1, 2, 3} if contains(table, 3) then print("Value found") end 
+3
source share

All Articles