Lua: expected table, zero

So, I had a problem when trying to split the rows into tables (team players). When there are only two players, it works like a charm, but when there are 3+ players, it pops up: "Init Error: transformice.lua: 7: bad argument: table expected, got nil". Everything seems to be in order, I really don't know what happened. Can you guys help me? Thank you Here is my code:

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 
+6
source share
1 answer

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

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

Will be evaluated:

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

What then will end:

 table.insert(teams[0],player) 

And teams[0] will be nil . You should write this as:

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

instead.

+9
source

Source: https://habr.com/ru/post/955679/


All Articles