了解 C 循环中的多个条件
一段 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将数组想象为循环缓冲区。
i
是当前项目,j
始终是前一项:Demo< /a>:
Imagine an array as a circular buffer.
i
is the current item andj
is always the previous one:Demo:
我不懂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
不,
j
始终比i
小 1,除非i
等于0
,然后j
> 是n-1
。因此,j = i+1
可能应该是j = i
,因为i
将在下一次迭代中增加。我不了解Lua所以我不能确定。
No,
j
is always one less thani
unlessi
equals0
, thenj
isn-1
. Soj = i+1
should probably bej = i
asi
will be increased in the next iteration.I don't know Lua so I can't be sure.
将其转换为 lua for 循环可能不是最好的;使用 while 循环:
并不是说代码有很多意义......如果您想转换为基于 1 的索引,请使用 i 、 j = 1 、 n 和 i<= n
Probably not best to transform it into a lua for loop; use a while loop:
Not that the code makes alot of sense.... if you want to convert to 1 based indexing as well use
i , j = 1 , n
andi<=n