Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: Table expected, got nil

Tags:

lua

lua-table

So, I’m having an issue while trying to split strings into tables (players into teams). When there are two players only, it works like a charm, but when there are 3+ players, this pops up: “Init Error : transformice.lua:7: bad argument: table expected, got nil”. Everything seems to be ok, I really don’t know what’s wrong. Can you guys please help me? Thanks! 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
like image 205
luafreak Avatar asked Oct 10 '13 14:10

luafreak


1 Answers

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.

like image 196
Nabren Avatar answered Oct 12 '22 14:10

Nabren