我能够从一个文件中读入并设置一个表但是如何创建它以便每个新表槽的第一个单词是一个键?
-- see if the file exists
function file_exists(file)
local f = io.open("data.txt", "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then return {} end
lines = {}
for line in io.lines("data.txt") do
lines[#lines + 1] = line
end
return lines
end
local lines = lines_from(file)
-- print all line numbers and their contents
for k,v in pairs(lines) do
print('line[' .. k .. ']', v)
end
答案 0 :(得分:3)
这取决于你如何定义单词。如果它是英文字母序列,那么你可以使用这样的东西:
function lines_from(file)
if not file_exists(file) then return {} end
lines = {}
for line in io.lines("data.txt") do
first_word = string.match(line, "%a+") -- word
lines[first_word] = line
end
return lines
end