user4225242
user4225242

Reputation:

[Lua]: Dividing numbers through two tables

What I have is two tables; One contains an unspecified amount of numbers, as well as the second table. What I'm trying to do is have the first table divide every number value in it by every number value in the second table. I've tried the following as it's all I can think that would have worked, but it does not as it tells me I am trying to perform an arithmetic on a nil value;

function findFactors( num )
    local factors = { }
    local x = 0
    while ( x < num ) do
        x = x + 1
        if ( num % x == 0 ) then
            table.insert( factors, "±" .. x )
        end
    end
    return factors
end

function findZeros( a, b, c )
    local zeros = { }
    local constant = findFactors( c )
    if ( a >= 2 ) then
        local coefficient = findFactors(a)
        for _, firstChild in pairs( constant ) do
            for _, secondChild in pairs( coefficient ) do
                local num1, num2 = tonumber( firstChild ), tonumber( secondChild )
                if num1 and num2 then
                    table.insert( zeros, (num1 / num2) )
                end
            end
        end
        print( table.concat (zeros, ",") )
    elseif a < 2 then
        print( table.concat (constant, ",") )
    end
end

findZeros( 3, 4, 6 )

I can't seem to find a way to do what I'm trying to actually do as I'm fairly new to lua. Any help on how to divide number values between two tables would be greatly appreciated.

Upvotes: 0

Views: 495

Answers (1)

Yu Hao
Yu Hao

Reputation: 122493

table.insert( factors, "±" .. x )

Here, you are inserting into factors a string like "±1", "±2", etc. That's not valid number representation. If you want to insert both positive and negative numbers, try this:

table.insert(factors, x)
table.insert(factors, -x)

Note here x and -x are numbers, not strings, so you can omit the call of tonumber in findZeros.

Upvotes: 1

Related Questions