Josh
Josh

Reputation: 13

With LUA: How to I remove an item from a table?

I can't seem to find a question quite like this.

I have a script that I've used to generate player names (for a game), it correctly stores names into a text file (players.txt) by appending the end of the file as they enter the game. No sorting. For instance:

Player1
Player4
Player3
Player2

How can I remove Player3 from the text file?

I do have a variable called currPlayers which is a table created from Players.txt that I want to use later on. Should I search the table and have the whole file rewritten as players leave or just search the file itself? Not sure which would be better.

Upvotes: 1

Views: 495

Answers (1)

There's two different ways that you could have the players in a table.

Option 1:

players = {Player1 = true, Player4 = true, Player3 = true, Player2 = true}
-- or equivalently
players['Player1'] = true
players['Player4'] = true
players['Player3'] = true
players['Player2'] = true

If that's how your table is set up, then just do players['Player3'] = nil to remove Player3.

Option 2:

players = {'Player1', 'Player4', 'Player3', 'Player2'}
-- or equivalently
players[1] = 'Player1'
players[2] = 'Player4'
players[3] = 'Player3'
players[4] = 'Player2'

If that's how your table is set up, then use an ipairs loop and table.remove to remove Player3, like this:

for k,v in ipairs(players) do
    if v == 'Player3' then
        table.remove(players, k)
        break
    end
end

Upvotes: 1

Related Questions