[Lua]:将数字分成两个表格

时间:2014-11-07 02:29:39

标签: math 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相当新鲜。任何有关如何在两个表之间划分数值的帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

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

在这里,您要在factors中插入"±1""±2"等字符串。这不是有效的数字表示。如果要插入正数和负数,请尝试以下操作:

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

请注意x-x是数字,而不是字符串,因此您可以省略tonumberfindZeros的调用。