Lua:期望是表格,但得到了空值(nil)。

所以,我在尝试将字符串拆分为表格(玩家分为团队)时遇到了问题。当只有两个玩家时,它可以完美运行,但当有3个或更多玩家时,出现以下错误:“_Init Error: transformice.lua:7:bad argument:table expected, got nil_”。一切似乎都没有问题,我真的不知道哪里出了问题。你们能帮帮我吗?谢谢!这是我的代码:

ps = {"Player1","Player2","Player3","Player4"}
local teams={{},{},{}}

--[[for name,player in pairs(tfm.get.room.playerList) do
 table.insert(ps,name)
 end]]

table.sort(ps,function() return math.random()>0.5 end)
for i,player in ipairs(ps) do
  table.insert(teams[i%#teams],player)
  end
点赞
用户2864945
用户2864945

Lua arrays start at index 1, not 0. In the case of when you have 3 players this line:

table.insert(teams[i%#teams],player)

Would evaluate to:

table.insert(teams[3%3],player)

Which then would end up being:

table.insert(teams[0],player)

And teams[0] would be nil. You should be able to write it as:

table.insert(teams[i%#teams+1],player)

instead.

Lua 数组索引从 1 开始,而不是 0。当有 3 个玩家时,这一行代码:

table.insert(teams[i%#teams],player)

会被计算成:

table.insert(teams[3%3],player)

然后就会变成:

table.insert(teams[0],player)

而且 teams[0] 将会是 nil。相反,你应该这样写:

table.insert(teams[i%#teams+1],player)

就可以了。

2013-10-10 14:57:06