Home > OS >  How to transform a text into an array in lua
How to transform a text into an array in lua

Time:06-22

Hey i'm trying to transform a text file into an array,

tutorial:gf
bopeebo:dad
fresh:dad
dadbattle:dad
spookeez:spooky

Result:

songs=['tutorial','bopeebo','fresh','dadbattle','spokeez']
characters=['gf','dad','dad','dad','spooky']

CodePudding user response:

The simplest way to do this would be to use io.lines(filename) to loop over the lines, using string.match to extract each k-v pair:

local songs, characters = {}, {}
for line in io.lines(filename) do
    -- Uses .* to allow empty keys and values; use .  instead to disallow
    local song, character = line:match"(.*):(.*)"
    table.insert(songs, song)
    table.insert(characters, character)
end

I would however question whether two lists are the right data structure for the job. You'll probably want to leverage the hash part of the table instead:

local character_by_song = {}
for line in io.lines(filename) do
    local song, character = line:match"(.*):(.*)"
    character_by_song[song] = character
end

This would allow you to look up which character is assigned to a specific song very efficiently (in constant time).

  • Related