了解 C 循环中的多个条件

发布于 2024-12-14 02:37:12 字数 310 浏览 1 评论 0原文

一段 C 代码

int i, j = 0;
for (i = 0, j = n-1; i < n; j = i++) {
    // array operations
}

我试图将

local j = n-1
for i = 1, n do -- arrays are 1-based in Lua
    -- array operations
    j = i+1
end

转换为 Lua 代码,但由于某种原因 Lua 代码不起作用。我的 C 循环正确吗?

There is a piece of C code

int i, j = 0;
for (i = 0, j = n-1; i < n; j = i++) {
    // array operations
}

that I'm trying to convert into Lua code

local j = n-1
for i = 1, n do -- arrays are 1-based in Lua
    -- array operations
    j = i+1
end

but for some reason Lua code doesn't work. Am I getting that C loop right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

颜漓半夏 2024-12-21 02:37:12

将数组想象为循环缓冲区。 i 是当前项目,j 始终是前一项:

n = 5
local j = n
for i = 1, n do -- arrays are 1-based in Lua
    -- array operations
    io.write('i=', i, ' j=', j, '\n')
    j = i
end

Demo< /a>:

i=1 j=5
i=2 j=1
i=3 j=2
i=4 j=3
i=5 j=4

Imagine an array as a circular buffer. i is the current item and j is always the previous one:

n = 5
local j = n
for i = 1, n do -- arrays are 1-based in Lua
    -- array operations
    io.write('i=', i, ' j=', j, '\n')
    j = i
end

Demo:

i=1 j=5
i=2 j=1
i=3 j=2
i=4 j=3
i=5 j=4
森罗 2024-12-21 02:37:12

我不懂Lua,但C代码的作用是:

在每次迭代时:

将i分配给j:j = i;
然后将 i 加 1:i = i+1;

看起来你的 Lua 代码应该是 j = i 而不是 j = i+1

I do not know Lua but what the C code does is:

At every iteration:

Assign i to j: j = i;
Then increment i by 1: i = i+1;

Looks like your Lua code should be j = i instead of j = i+1

年华零落成诗 2024-12-21 02:37:12

不,j 始终比 i 小 1,除非 i 等于 0,然后 j > 是n-1。因此,j = i+1 可能应该是 j = i,因为 i 将在下一次迭代中增加。

我不了解Lua所以我不能确定。

No, j is always one less than i unless i equals 0, then j is n-1. So j = i+1 should probably be j = i as i will be increased in the next iteration.

I don't know Lua so I can't be sure.

独守阴晴ぅ圆缺 2024-12-21 02:37:12

将其转换为 lua for 循环可能不是最好的;使用 while 循环:

local i , j = 0 , n-1
while i < n do
    --array operations
    j = i
    i = i + 1
end

并不是说代码有很多意义......如果您想转换为基于 1 的索引,请使用 i 、 j = 1 、 n 和 i<= n

Probably not best to transform it into a lua for loop; use a while loop:

local i , j = 0 , n-1
while i < n do
    --array operations
    j = i
    i = i + 1
end

Not that the code makes alot of sense.... if you want to convert to 1 based indexing as well use i , j = 1 , n and i<=n

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文