Lua:表预期,得到零

标签 lua lua-table

因此,我在尝试将字符串拆分为表格(玩家拆分为团队)时遇到了问题。当只有两个玩家时,它就像一个魅力,但是当有 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

最佳答案

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)

反而。

关于Lua:表预期,得到零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19299162/

相关文章:

lua - 'nil' 作为 Lua 表中的一个元素?

string - 检查 lua 中表中的字符串值

lua - Torch 中的集群

sockets - 如何实时接收来自服务器的消息

arrays - 数组上的 Lua 展开运算符

Lua 表作为 redis 参数

lua - 从 Lua 中的表中获取所有重复项

lua - 如何使用 Lua 脚本在 Redis 中操作数字

string - 高效分割字符串

parsing - 将 CSV 文件转换为在 Lua 中定义键的表