使用io.lines可以读取文件的内容, 返回一个函数.
每次调用这个函数, 按照格式要求输出文件的内容.
格式如下 :
例如 :
多字节字符, 使用数字返回, 必须要复合字节数, 否则会有问题.
[参考]
"*n": reads a number; this is the only format that returns a number instead of a string.
"*a": reads the whole file, starting at the current position. On end of file, it returns the empty string.
"*l": reads the next line skipping the end of line, returning nil on end of file. This is the default format.
"*L": reads the next line keeping the end of line (if present), returning nil on end of file.
number: reads a string with up to this number of bytes, returning nil on end of file. If number is zero, it reads nothing and returns an empty string, or nil on end of file.
例如 :
[root@db-172-16-3-150 ~]# pwd
/root
[root@db-172-16-3-150 ~]# ll install.log
-rw-r--r--. 1 root root 41261 Sep 26 15:30 install.log
[root@db-172-16-3-150 ~]# lua
Lua 5.2.3 Copyright (C) 1994-2013 Lua.org, PUC-Rio
> f = io.lines("/root/install.log", "*l") -- "*l"每次读取一行, 不添加回车.
> print(type(f)) -- f是一个函数
function
> print( f() ) -- 调用f函数, 每次返回一行, 不添加回车.
Installing libgcc-4.4.7-3.el6.x86_64
> print( f() )
warning: libgcc-4.4.7-3.el6.x86_64: Header V3 RSA/SHA1 Signature, key ID c105b9de: NOKEY
> print( f() )
Installing ca-certificates-2010.63-3.el6_1.5.noarch
> f = io.lines("/root/install.log", "*L") -- "*L" 每次返回一行, 同时加一个回车.
> print( f() )
Installing libgcc-4.4.7-3.el6.x86_64
> print( f() )
warning: libgcc-4.4.7-3.el6.x86_64: Header V3 RSA/SHA1 Signature, key ID c105b9de: NOKEY
> f = io.lines("/root/install.log", 5) -- 数字表示每次读取多少个字节, 如果是多字节字符可能有问题.
> print( f() )
Insta
> print( f() )
lling
> f = io.lines("/root/install.log", "*a") -- "*a" 表示一次读取文件的所有内容
> print( f() )
Installing libgcc-4.4.7-3.el6.x86_64
warning: libgcc-4.4.7-3.el6.x86_64: Header V3 RSA/SHA1 Signature, key ID c105b9de: NOKEY
Installing ca-certificates-2010.63-3.el6_1.5.noarch
... 略
多字节字符, 使用数字返回, 必须要复合字节数, 否则会有问题.
[root@db-172-16-3-150 ~]# vi test.lua
你好test=100
return test
[root@db-172-16-3-150 ~]# lua
Lua 5.2.3 Copyright (C) 1994-2013 Lua.org, PUC-Rio
> f = io.lines("/root/test.lua", 2)
> print( f() ) -- 因为UTF-8中文使用了3个字节, 所以返回有问题.
位
> print( f() )
?半>
> print( f() )
¥?
> print( f() )
te
> print( f() )
st
-- 使用3个字节, 正常返回存储的中文.
> f = io.lines("/root/test.lua", 3)
> print( f() )
你
> print( f() )
好
> print( f() )
tes
[参考]