|
| 1 | +-- Get the filename from the command line argument |
| 2 | +local inputFilePath = arg[1] |
| 3 | + |
| 4 | +if not inputFilePath then |
| 5 | + print("Usage: lua script.lua <filename>") |
| 6 | + return |
| 7 | +end |
| 8 | + |
| 9 | +-- Define the output file path |
| 10 | +local outputFilePath = inputFilePath:gsub("%.%w+$", "_results.txt") |
| 11 | + |
| 12 | +-- Function to split a string by a given delimiter |
| 13 | +local function split(inputstr, sep) |
| 14 | + if sep == nil then |
| 15 | + sep = "%s" |
| 16 | + end |
| 17 | + local t = {} |
| 18 | + for str in string.gmatch(inputstr, "([^"..sep.."]+)") do |
| 19 | + table.insert(t, str) |
| 20 | + end |
| 21 | + return t |
| 22 | +end |
| 23 | + |
| 24 | +-- Open the input file in read mode |
| 25 | +local inputFile, err = io.open(inputFilePath, "r") |
| 26 | + |
| 27 | +-- Check if the file was opened successfully |
| 28 | +if not inputFile then |
| 29 | + print("Could not open input file: " .. err) |
| 30 | + return |
| 31 | +end |
| 32 | + |
| 33 | +-- Read the first line (numbers) |
| 34 | +local numberLine = inputFile:read("*l") |
| 35 | + |
| 36 | +-- Read the second line (texts) |
| 37 | +local textLine = inputFile:read("*l") |
| 38 | + |
| 39 | +-- Close the input file |
| 40 | +inputFile:close() |
| 41 | + |
| 42 | +-- Split the lines by commas |
| 43 | +local numbers = split(numberLine, ",") |
| 44 | +local texts = split(textLine, ",") |
| 45 | + |
| 46 | +-- Create a table to store the number-text pairs |
| 47 | +local numberTextTable = {} |
| 48 | + |
| 49 | +-- Populate the table |
| 50 | +for i = 1, #numbers do |
| 51 | + local number = tonumber(numbers[i]:match("^%s*(.-)%s*$")) |
| 52 | + local text = texts[i]:match("^%s*(.-)%s*$") |
| 53 | + table.insert(numberTextTable, {number = number, text = text}) |
| 54 | +end |
| 55 | + |
| 56 | +-- Sort the table by text first, then by number if the texts are the same |
| 57 | +table.sort(numberTextTable, function(a, b) |
| 58 | + if a.text == b.text then |
| 59 | + return a.number < b.number |
| 60 | + else |
| 61 | + return a.text < b.text |
| 62 | + end |
| 63 | +end) |
| 64 | + |
| 65 | +-- Open the output file in write mode |
| 66 | +local outputFile, err = io.open(outputFilePath, "w") |
| 67 | + |
| 68 | +-- Check if the file was opened successfully |
| 69 | +if not outputFile then |
| 70 | + print("Could not open output file: " .. err) |
| 71 | + return |
| 72 | +end |
| 73 | + |
| 74 | +-- Write the table to the output file |
| 75 | +outputFile:write("{\n") |
| 76 | +for _, pair in ipairs(numberTextTable) do |
| 77 | + outputFile:write(" [" .. pair.number .. "] = \"" .. pair.text .. "\",\n") |
| 78 | +end |
| 79 | +outputFile:write("}\n") |
| 80 | + |
| 81 | +-- Close the output file |
| 82 | +outputFile:close() |
| 83 | + |
| 84 | +print("Table successfully written to " .. outputFilePath) |
0 commit comments