Search code examples
sortingluabubble-sort

Got an error that I can't compare nil to number even though I is a number


I am trying to do a simple bubble sort (My code probably looks unprofessional but I'm just learning) and in my bubble sort function I get an error code saying I can't compare nil to number even though all the values in my table should be numbers.


local function bubblesort(array)
    for getal = 1, #array do
    for i = 1, #array do
      if array[i] > array[i + 1] then
        local temp = array[i]
        array[i + 1] = array[i]
        array[i + 1] = temp
      end
    end
  end
  return array
end

if you need to see it, here's the rest of the code to make the table and print it out


local function printtabel(tabel)
    for _,v in pairs(tabel) do
        io.write(v..' ')
    end
    print()
end

io.write("Geef seed, grootte en max: ")
local SEED = io.read("*n")
local GROOTTE = io.read("*n")
local MAX = io.read("*n")

math.randomseed(SEED)
local t = {} 
for n = 1,GROOTTE do
    t[n] = math.random(1,MAX)
end
bubblesort(t)
printtabel(t)


Solution

  • I get an error code saying I can't compare nil to number even though all the values in my table should be numbers

    Well, computers don't just make things up so it is trying to compare a number and nil. If all the values in your table are numbers, it's getting nil from somewhere and not one of the values in your table.

    When trying to find out errors for something this simple, it can be helpful to create a very small sample and print the outputs to make sure everything is what you expect it to be inside the loop. You can click on this to view and run the sample code online. The results:

    i = 1, array[i] = 2
    i+1 = 2, array[i+1] = 5
    i = 2, array[i] = 5
    i+1 = 3, array[i+1] = 1
    i = 3, array[i] = 5
    i+1 = 4, array[i+1] = nil
    /var/task/bin/lua: main.lua:6: attempt to compare nil with number
    

    So you can see there is a big in your function. There are three values in the sample array and you are looping i from 1 to 3, but you are comparing array[i] with array[i+1] in your loop. That means that when i is 3, you are comparing with array[4]. In lua you can access elements outside the array length, but they return nil.

    Just stepping through the code in your mind using a simple input or adding print statements to see what is actually being used is a great way to debug code that doesn't work the way you think it should.