0

I'm creating a gaming server that allows Lua scripts. Basically, the script gets the server date and selects a text file based on that date. Each text file contains a list of names. The point of the script is to rename players a "fun" holiday name.

This is my initial code to populate a table and assign a name:

-- Get Names from selected Holiday file
local holFile = io.open(filePath .. holiday .. ".txt", "r");
local holidayNames = {}

for line in holFile:lines() do
    table.insert (holidayNames, line);
end

-- Set Name to a random item in the Holiday Names table
randomItem = math.random(0, #holidayNames - 1)
Name = (holidayNames[randomItem])

I also added this part BEFORE the above code just to have a table populated with current names:

-- Get Current Players List
local currPlayers = io.open(filePath "players.txt", "r");
local currentPlayers = {}

for line in currPlayers:lines() do
    table.insert (currentPlayers, line);
end

So basically, as I'm attempting to add items to holidayNames, I want to see if they exist in currentPlayers, first.

Unheilig
  • 16,196
  • 193
  • 68
  • 98
Josh
  • 13
  • 3

1 Answers1

0

Since currentPlayers is already defined, you'll have to scan it per each line in holiday names to look for a match. You can do this using pairs:

for line in holFile:lines() do
    for __, name in pairs(currentPlayers) do
        if name ~= line then
            -- skip insertion if it's a match
            table.insert(holidayNames, line)
        end
    end
end
Optimum
  • 146
  • 2
  • 11
  • To clarify, the idea is to get currPlayers, THEN assign a random name based on holFile, skipping any names found in currPlayers to avoid two players with the same name. On a side note, a player entering the server with the same name is already automatically renamed a generic name, something I'd like to avoid. Is this what your answer does? Just confirming. Thanks. – Josh May 14 '20 at 20:18
  • Ohh, OK, this won't work then. However, if you don't care about maintaining the holidayNames, you can remove the random Name from holidayNames after assigning it like so: `holidayNames[randomItem], holidayNames[#holidayNames] = holidayNames[#holidayNames], nil` This way holidayNames will always contain unique names and remain a contiguous array. If you need the full array again, you'll have to reload it. – Optimum May 15 '20 at 16:11
  • I'm thinking that I SHOULDN'T maintain holidayNames. Lets say a player joins at 11:50 pm on a holiday then another joins at 12:10 am. I don't want the player joining after midnight to be reassigned a holidayName, granted the script looks for the date/time at the time the player joins, then assigns a holidayName if necessary. I should probably keep currPlayers in memory, to be able to compare the two when new players join and then write to a text file the current players (add/remove). – Josh May 18 '20 at 08:14