name address email
5
0
3 回答
11
Lua patternsについて読んでください。これはhttp://www.lua.org/pil/20.html[string library]の一部です。 以下は関数の例です(テストされていません):
function read_addresses(filename) local database = { } for l in io.lines(filename) do local n, a, e = l:match '(%S+)%s+(%S+)%s+(%S+)' table.insert(database, { name = n, address = a, email = e }) end return database end
この関数は、非スペース( %S
)文字で構成される3つの部分文字列を取得するだけです。 実際の関数には、パターンが実際に一致することを確認するためのエラーチェックがあります。
9
urocの答えを拡張するには:
local file = io.open("filename.txt") if file then for line in file:lines() do local name, address, email = unpack(line:split(" ")) --unpack turns a table like the one given (if you use the recommended version) into a bunch of separate variables --do something with that data end else end --you'll need a split method, i recommend the python-like version at http://lua-users.org/wiki/SplitJoin --not providing here because of possible license issues
ただし、名前にスペースが含まれている場合には対応できません。
3
入力ファイルの形式を制御できる場合は、http://www.lua.org/pil/12.html [こちら]で説明されているように、Lua形式でデータを保存することをお勧めします。
そうでない場合は、http://www.lua.org/pil/21.2.html [io library]を使用してファイルを開き、http://www.lua.org/pil/20.html [string library ]のような:
local f = io.open("foo.txt") while 1 do local l = f:read() if not l then break end print(l) -- use the string library to split the string end