Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua Check for Value Against Array Elements

Trying to teach myself Lua; I've gone through similar questions about this, and I still can't understand how to do this. The main thing that is confusing me is tables vs arrays. For the below code I'm just wanting check a given value against values I've populated into an array. However, something is going wrong. Thank for your time.

valueToCheckFor = 35    

sampleArray = {}
for i=30, 49, 1  do
  sampleArray[i] = i + 1
  print(i)
end    

for k = 0, #sampleArray, 1 do
    if valueToCheckFor == k then
        print(valueToCheckFor .. " is in the array.")
    else
        print(valueToCheckFor .. " is not in the array.")
    end
end
like image 442
John Specko Avatar asked May 30 '26 08:05

John Specko


1 Answers

Here is your code written to be Lua array friendly:

valueToCheckFor = 35

sampleArray = {}
for i=30, 49  do
    -- add to end of array
    sampleArray[#sampleArray+1] = i + 1
    print(i+1)
end

-- check each value in array
for k = 1, #sampleArray do
    if valueToCheckFor == sampleArray[k] then
        print(valueToCheckFor .. " is in the array.")
    else
        print(valueToCheckFor .. " is not in the array.")
    end
end
like image 114
gwell Avatar answered Jun 02 '26 02:06

gwell