lua io操作


lua io操作

       

           

                                 

io 操作

        

相关函数

io.close(file):关闭文件,file可选,如果没有指定,关闭默认的文件
io.flush():刷新文件

io.input ([file]):设置默认输入文件,io.read从文件中读取内容
io.output ([file]):设置默认的输出文件,io.write向文件中写入内容

io.write (···):向默认文件中写入内容,...为字符串(写入文件的内容)

io.lines ([filename, ···]):以可读模式打开文件,每次返回一行数据
                            当到文件尾时,将返回nil,但不关闭文件
                            如不指定filename,则从控制态读取数据

       

io.read(format):读取文件内容的格式

Reads the file file, according to the given formats, which specify what to read. 
For each format, the function returns a string or a number with the characters 
read, or fail if it cannot read data with the specified format. (In this latter 
case, the function does not read subsequent formats.) When called without 
arguments, it uses a default format that reads the next line (see below).
* 根据指定的格式读取文件内容

The available formats are
    "n": reads a numeral and returns it as a float or an integer, following the 
lexical conventions of Lua. (The numeral may have leading whitespaces and a sign.) 
This format always reads the longest input sequence that is a valid prefix for a 
numeral; if that prefix does not form a valid numeral (e.g., an empty string, "0x", 
or "3.4e-") or it is too long (more than 200 characters), it is discarded and the 
format returns fail.
    "a": reads the whole file, starting at the current position. On end of file, it 
returns the empty string; this format never fails.
    "l": reads the next line skipping the end of line, returning fail on end of 
file. This is the default format.
    "L": reads the next line keeping the end-of-line character (if present), 
returning fail on end of file.
    number: reads a string with up to this number of bytes, returning fail on end 
of file. If number is zero, it reads nothing and returns an empty string, or fail 
on end of file.
 * n:读取一个数字并返回它。例:io.read("n")
 * a:从当前位置读取整个文件。例:io.read("a")
 * l:读取下一行,跳过文件结束符,在文件尾 (EOF) 处返回 nil。例:io.read("l")
 * L:读取下一行,保留文件结束符,在文件尾 (EOF) 处返回 nil。例:io.read("L")
 * number:返回一个指定字符个数(字节单位)的字符串,或在 EOF 时返回 nil。例:io.read(5)
 
The formats "l" and "L" should be used only for text files. 
 * l、L只应该用在文本文件中

          

io.open(filename, mode):按照指定模式打开文件,mode可选

# io.open (filename [, mode]):按照指定模式打开文件
This function opens a file, in the mode specified in the string mode. 
In case of success, it returns a new file handle.
* 该函数以指定模式打开文件,返回一个新的文件句柄

The mode string can be any of the following:
    "r": read mode (the default);
    "w": write mode;
    "a": append mode;
    "r+": update mode, all previous data is preserved;
    "w+": update mode, all previous data is erased;
    "a+": append update mode, previous data is preserved, 
          writing is only allowed at the end of file.
 * r:以只读形式打开文件(默认)
 * w:以致谢形式打开文件
 * a:以追加模式打开文件
 * r+:更新模式(可读写),之前数据会保留
 * w+:更新模式(可读写),之前所有数据会清空
 * a+:追加更新模式(可读写),之前所有数据会保留
 * +:表示既可以读,也可以写

The mode string can also have a 'b' at the end, which is needed 
in some systems to open the file in binary mode. 
* 如果模式以b结尾,表示以2进制形式打开二进制文件

          

io.tmpfile ():返回一个临时文件句柄,该文件以更新模式打开,程序结束时自动删除

# io.tmpfile ():返回一个临时文件句柄,该文件以更新模式打开,程序结束时自动删除
In case of success, returns a handle for a temporary file. 
This file is opened in update mode and it is automatically 
removed when the program ends. 

        

io.type(obj):检查是否是一个有效的文件句柄

# io.type (obj):检查是否是一个有效的文件句柄,返回:file、closed file、fail
Checks whether obj is a valid file handle. 
Returns the string "file" if obj is an open file handle, 
"closed file" if obj is a closed file handle, 
or fail if obj is not a file handle. 

        

io.popen (prog, mode):在另外的程序中打开文件,返回文件句柄

# io.popen (prog [, mode]):在另外的程序中打开文件,返回文件句柄
                            该函数依赖于系统,部分平台不支持
This function is system dependent and is not available on all platforms.
Starts the program prog in a separated process and returns a file handle 
that you can use to read data from this program (if mode is "r", the default) 
or to write data to this program (if mode is "w"). 

        

                       

                                 

使用示例

        

示例:io.read

Lua 5.4.4  Copyright (C) 1994-2022 Lua.org, PUC-Rio
-- 以默认模式(只读模式)打开文件
> file=io.open("file")

-- 设置默认输入源为file(默认是控制台)
> io.input(file)
file (0x7ff85cfd4880)

-- 读取第一行
> io.read()
瓜田李下

-- 读取第二行
> io.read()
瓜田李下2


-- 读取第三行(保留文件分隔符),多出一个行
> io.read("L")
瓜田李下3


-- 读取第四行(保留文件分隔符),多出一个行
> io.read("*L")
瓜田李下4


-- 继续读取,没有文件内容,输出nil
> io.read("L")
nil

         

示例:io.read("n")

huli@hudeMacBook-Pro ~ % cat file4
2
323
12131
2322

huli@hudeMacBook-Pro ~ % lua      
Lua 5.4.4  Copyright (C) 1994-2022 Lua.org, PUC-Rio
> file=io.open("file4")
> io.input(file)
file (0x7ff8462c8880)

-- 读取连续的数字行数据
> io.read("n")
2
> io.read("n")
323
> io.read("n")
12131
> io.read("n")
2322
> io.read("n")
nil
> io.read("n")
nil

         

示例:io.read("n")

huli@hudeMacBook-Pro ~ % cat file4
2
323
瓜田李下
2322

huli@hudeMacBook-Pro ~ % lua      
Lua 5.4.4  Copyright (C) 1994-2022 Lua.org, PUC-Rio
> file=io.open("file4")
> io.input(file)
file (0x7ff8462c8880)

-- 读取连续的数字行数据,如不连续则终止,或者读到最后一行
> io.read("n")
2
> io.read("n")
323
> io.read("n")
nil
> io.read("n")
nil
> io.read("n")
nil
> io.read("n")
nil

          

示例:io.write

Lua 5.4.4  Copyright (C) 1994-2022 Lua.org, PUC-Rio
-- 打开文件
> file=io.open("file","w")

-- 设置输出源为file
> io.output(file)
file (0x7ff85cfd4880)

-- 写入文件
> io.write("瓜田李下 gtlx")
file (0x7ff85cfd4880)

-- 需执行flush操作,否则不会输出到文件
> io.flush()
true

-- 退出后,查看文件内容
huli@hudeMacBook-Pro ~ % cat file
瓜田李下 gtlx%                                                                  

         

示例:io.lines(filename)

Lua 5.4.4  Copyright (C) 1994-2022 Lua.org, PUC-Rio
-- 不指定文件,默认从控制台读取数据
> io.lines()
function: 0x600002d4c000
> for value in io.lines() do print(value) end
hello
hello
hello2
hello2


-- 指定读取的文件
> for value in io.lines("file") do print(value) end
瓜田李下
瓜田李下2
瓜田李下3
瓜田李下4
瓜田李下5
瓜田李下6

        

               

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Lua 是一种轻量级的脚本语言,它具有简洁、高效、易于扩展等特点。Lua 可以被嵌入到 C/C++ 应用程序中,也可以作为独立的解释器运行。下面简单介绍一下 Lua 脚本的基本语法和用法。 ## 1. 基本语法 Lua 语言的基本语法与众多编程语言类似。下面是一个简单的 Lua 脚本示例: ```lua -- 定义变量 a = 10 b = 20 -- 条件语句 if a < b then print("a is less than b") else print("a is greater than or equal to b") end -- 循环语句 for i = 1, 10 do print(i) end -- 函数定义 function add(a, b) return a + b end -- 函数调用 sum = add(a, b) print("sum =", sum) ``` ## 2. 常用函数 Lua 中内置了一些常用的函数,比如字符串处理函数、数学函数、文件操作函数等。下面是一些常用函数的示例: ```lua -- 字符串处理函数 str = "hello world" print(string.upper(str)) -- 将字符串转换为大写 print(string.sub(str, 1, 5)) -- 截取字符串 -- 数学函数 print(math.pow(2, 3)) -- 求幂 print(math.sqrt(16)) -- 求平方根 -- 文件操作函数 file = io.open("test.txt", "w") file:write("Hello World") file:close() file = io.open("test.txt", "r") print(file:read("*all")) file:close() ``` ## 3. Lua 与 C/C++ 的交互 Lua 可以被嵌入到 C/C++ 应用程序中,实现 Lua 脚本与 C/C++ 代码的交互。在 C/C++ 中,可以使用 Lua API 调用 Lua 脚本中的函数、读写变量等。下面是一个简单的示例: ```c #include "lua.hpp" int main() { lua_State* L = luaL_newstate(); luaL_openlibs(L); luaL_dofile(L, "test.lua"); // 执行 Lua 脚本 lua_getglobal(L, "add"); // 获取 Lua 函数 lua_pushnumber(L, 10); // 压入参数 lua_pushnumber(L, 20); lua_call(L, 2, 1); // 调用函数,2 表示有两个参数,1 表示有一个返回值 double result = lua_tonumber(L, -1); // 获取返回值 printf("result = %lf\n", result); lua_close(L); return 0; } ``` 上面的示例中,C/C++ 代码使用 Lua API 调用了 Lua 脚本中的 add 函数,并获取了该函数的返回值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值