3

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
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • possible duplicate of [Search for an item in a Lua list](http://stackoverflow.com/questions/656199/search-for-an-item-in-a-lua-list) – hjpotter92 Apr 08 '14 at 20:18

3 Answers3

1

You sampleArray is not a sequence because does not begin at 1 and so # cannot be used on it. See http://www.lua.org/manual/5.2/manual.html#3.4.6.

lhf
  • 70,581
  • 9
  • 108
  • 149
1

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
gwell
  • 2,695
  • 20
  • 20
  • @babyy on SO people aim to always backup their statements, that's how we all learn from each other. Truth is I don't see anything wrong with the stated soln, except that author should have explained what was wrong (which other answers have done, but they didn't provide fix). – Oliver Apr 08 '14 at 23:41
0

#sampleArray return 0 because your array is not started by 1

The array part is every key that starts with the number 1 and increases up until the first value that is nil

https://stackoverflow.com/a/9613573/1198482

Community
  • 1
  • 1
Baba
  • 852
  • 1
  • 17
  • 31