【问题标题】:[Lua]: Dividing numbers through two tables[Lua]:通过两个表除数
【发布时间】:2014-11-07 11:11:10
【问题描述】:

我有两张桌子;一个包含未指定数量的数字,以及第二个表格。我要做的是让第一个表将其中的每个数值除以第二个表中的每个数值。我已经尝试了以下方法,因为这是我认为可行的方法,但它并没有告诉我我正在尝试对 nil 值执行算术;

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 还很陌生。任何有关如何在两个表之间划分数值的帮助将不胜感激。

【问题讨论】:

  • tableA: 1, 2, 3, 6 ; tableB: 1, 3. 如果我使用原帖中的代码,它不会做任何事情。

标签: math lua


【解决方案1】:
table.insert( factors, "±" .. x )

在这里,您正在向factors 插入一个字符串,如"±1""±2" 等。这不是有效的数字表示。如果你想同时插入正数和负数,试试这个:

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

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

【讨论】:

  • 这段时间我都忘了我加了那个,哈哈。谢谢。现在可以了。
猜你喜欢
  • 1970-01-01
  • 2012-02-02
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 2017-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多