Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to transform a text into an array in lua

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading