So i am having an Array in Lua, lets say:
local Array = {1, 8, 10, 15, 20, 30}
so now i want to know if a specific number is in the Array. So if did this:
local number = 4
if Array[number] then
print("Is in Array")
else
print("Not in Array")
end
I want to know if 4 is part of the array. It isent so expected output is Not in Array
but Lua takes the number as the position of the entery, there is an entery on position 4 so the output is Is in Array
How can i check if a specific number is part of the array without indexing numbers as strings?
CodePudding user response:
Your code doesn't do what you think it does. Let's walk through it:
local Array = {1, 8, 10, 15, 20, 30}
this is just syntactic sugar for
local Array = {[1] = 1, [2] = 8, [3] = 10, [4] = 15, [5] = 20, [6] = 30}
thus Array[4]
is 15
. This is how arrays work: You index an array using an index. An index is not to be confused with the value this gives you. In this example, 4
is the index and 15
is the value.
What you want isn't an array but rather a set. You can easily build a set in Lua by using the values as keys and using truthy values in a table:
local set = {[1] = true, [8] = true, [10] = true, [15] = true, [20] = true, [30] = true}
if you find this awkward to type, just write yourself an utility to turn an array into a set:
local function make_set(array)
local set = {}
for _, val in ipairs(array) do
set[val] = true
end
return set
end
set = make_set{1, 8, 10, 15, 20, 30}
You can then use this set to efficiently check whether it contains a number:
if set[number] then
print"is in set"
else
print"not in set"
end
Side notes:
- Alternatively to building a set, you could use a linear search. This would be less efficient if done multiple times and isn't even much more convenient to implement. Lua makes the use of a "set" as a special case of the table very easy.
Uppercase
in Lua is usually reserved for "class-like" tables, although there is no "official" naming convention.