1
votes

I have created a function that (pseudo)randomly creates a table containing numbers. I then loop this function until at least correct result is found. As soon as I've confirmed that at least one such result exists, I stop the function and return the table.

When I create tables containing small values, there are no issues. However, once the random numbers grow to the range of hundreds, the function begins to return nil, even though the table is true the line before I return it.

local sort = table.sort
local random = math.random

local aMin, aMax = 8, 12
local bMin, bMax = 200, 2000

local function compare( a, b )
    return a < b
end

local function getNumbers()
    local valid = false
    local numbers = {}

    -- Generate a random length table, containing random number values.
    for i = 1, random( aMin, aMax ) do
        numbers[i] = random( bMin, bMax )
    end
    sort( numbers, compare )

    -- See if a specific sequence of numbers exist in the table.
    for i = 2, #numbers do
        if numbers[i-1]+1 == numbers[i] or numbers[i-1] == numbers[i] then
            -- Sequence found, so stop.
            valid = true
            break
        end
    end

    for i = 1, #numbers-1 do
        for j = i+1, #numbers do
            if numbers[j] % numbers[i] == 0 and numbers[i] ~= 1 then
                valid = true
                break
            end
        end
    end

    if valid then
        print( "Within function:", numbers )
        return numbers
    else
        getNumbers()
    end
end

local numbers = getNumbers()
print( "Outside function:", numbers )

This function, to my understanding, is supposed to loop infinitely until I find a valid sequence. The only way that the function can even end, according to my code, is if valid is true.

Sometimes, more often than not, with large numbers the function simply outputs a nil value to the outside of the function. What is going on here?

2

2 Answers

2
votes

You're just doing getNumbers() to recurse instead of return getNumbers(). This means that if the recursion gets entered, the final returned value will be nil no matter what else happens.

2
votes

In the else case of the if valid then, you are not returning anything. You only return anything in the valid case. In the else case, a recursive call may return something, but then you ignore that returned value. The print you see is corresponding to the return from the recursive call; it isn't making it out the original call.

You mean to return getNumbers().