[Lua]: 通过两个表分割数字

我有两个表;一个包含未指定数量的数字,以及第二个表。我想做的是让第一个表中的每个数字值除以第二个表中的每个数字值。我尝试了下面的代码,但它没有成功,因为它告诉我我在尝试对空值进行算术运算;

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 )

由于我对Lua相当陌生,因此似乎找不到实际要做的事情的方法。任何关于如何在两个表之间分割数字值的帮助将不胜感激。

点赞
用户1009479
用户1009479

在这里,你在将一个类似于"±1""±2"等的字符串插入到factors中。这不是一个有效的数字表示方法。如果你想要插入正数和负数,可以尝试以下代码:

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

注意,这里的x-x是数字,不是字符串,因此在findZeros中可以省略对tonumber的调用。

2014-11-07 03:06:03