这是我的错误
Expected objects to be the same.
Passed in:
(table) {
[1] = 1
[2] = 2
[3] = 3
[4] = 4 }
Expected:
(nil)
Run Code Online (Sandbox Code Playgroud)
这是我的代码,请有人可以帮助我
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
Run Code Online (Sandbox Code Playgroud)
我尝试过使用 for 循环有人可以帮助我吗
该循环有几个问题需要修复才能使其正常工作:
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
Run Code Online (Sandbox Code Playgroud)
这应该可行,但在这些情况下,当您知道迭代次数时,最好使用循环for而不是while循环,因为它负责增加/减少循环变量:
local tbl = {}
for i = 1, a do tbl[i] = i end
return tbl
Run Code Online (Sandbox Code Playgroud)
你应该避免使用table作为变量名,因为它与 Lua 已经提供的表值冲突。