重构中

如何减少这些代码行数(如果可能的话)?

local function Run(steps)
    if steps < 0 then
        while steps < 0 do
            Foo()
            steps = steps + 1
        end
    else
        while steps > 0 do
            Bar()
            steps = steps - 1
        end
    end
end

Run(5)
Run(-8)

也许有一些性能更高效的方法?

点赞
用户1847592
用户1847592

你可以完全删除 if

local function Run(steps)
    while steps < 0 do
        Foo()
        steps = steps + 1
    end
    while steps > 0 do
        Bar()
        steps = steps - 1
    end
end

Run(5)
Run(-8)

或者你可以使用 for 循环代替 while:

local function Run(steps)
    for i = -1, steps, -1 do
        Foo()
    end
    for i = 1, steps, 1 do
        Bar()
    end
end

Run(5)
Run(-8)

但你在这里不会得到任何可测量的性能提升。

2021-04-04 11:21:11
用户2858170
用户2858170

你可以缩短那段代码,但我不认为有什么必要。代码应该易于阅读,而不是尽可能的短小。

唯一我会去掉的是 if 语句,因为条件也在 while 循环中。基于计数器的已知迭代次数的 while 循环可以被 Egor 解释的数值 for 循环所取代。

function Run(steps)
  local f = steps < 0 and Foo or Bar
  for i = 1, math.abs(steps) do f() end
end
2021-04-04 11:25:53