gpt4 book ai didi

Why my Lua table is error when l use while loop(L使用While循环时我的Lua表为什么出错)

转载 作者:bug小助手 更新时间:2023-10-28 10:58:09 26 4
gpt4 key购买 nike



here is my error

以下是我的错误


Expected objects to be the same.
Passed in:
(table) {
[1] = 1
[2] = 2
[3] = 3
[4] = 4 }
Expected:
(nil)

here is my code some one can help me please

这是我的代码,有人能帮我吗


local function between(a, b)
local table = {}
while not a == 5 do
local a = 1
table[a] = a
local a = a + 1
end
print(table)
end

return between

l have tried to use for loop
can someone help me please

L试着用FOR LOOP,有人能帮帮我吗


更多回答

Please edit the question to show how you're calling the function. The first problem I see is that not a will always be true or false, neither of which is equal to 5, so the loop won't run.

请编辑问题以显示您是如何调用该函数的。我看到的第一个问题是,不是a总是真或假,两者都不等于5,所以循环不会运行。

You should read a Lua tutorial about local variable's scope in Lua.

您应该阅读Lua教程,了解Lua中局部变量的作用域。

优秀答案推荐

There are several issues with the loop that need to be fixed to make it work:

需要修复该循环的几个问题才能使其工作:


local function between(a, b)
local table = {}
while a > 0 do
-- local a = 1 -- this is not needed, as it:
-- (1) creates a *new* `a` value, which shadows the original value without changing it
-- (2) is reset every loop iteration without any impact on the `a` value above
table[a] = a
-- local a = a + 1 -- this creates yet another `a` variable that is only visible
-- inside the loop, so doesn't have any impact on the `while` condition

-- since you already have the number of iterations you want to do (`a`)
-- you can simply keep subtracting from it until it reaches 0:
a = a - 1
end
-- it's better to return the value, as you may do something other than printing
return table
end

This should work, but in those cases when you know the number of iterations, it's better to use the for loop instead of the while loop, as it takes care of increasing/decreasing your loop variable:

这应该可以工作,但是在那些你知道迭代次数的情况下,最好使用for循环而不是while循环,因为它负责增加/减少你的循环变量:


local tbl = {}
for i = 1, a do tbl[i] = i end
return tbl

You should avoid using table as a variable name, as it clashes with the table value already provided by Lua.

您应该避免使用TABLE作为变量名,因为它与Lua已经提供的表值冲突。


更多回答

@IHML, You can approve the answer if it works for you.

@IHML,如果答案对您有效,您可以审批。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com