简体   繁体   English

如何在lua中将文本转换为数组

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

The simplest way to do this would be to use io.lines(filename) to loop over the lines, using string.match to extract each kv pair:最简单的方法是使用io.lines(filename)遍历行,使用string.match提取每个 kv 对:

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).这将允许您非常有效地(在恒定时间内)查找分配给特定歌曲的角色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM