-- 执行命令(返回状态码) local exit_code = os.execute("echo Hello from Lua") -- Windows 上用: -- os.execute("dir")
-- 捕获命令输出(需要自己封装) localfunctionexecute_command(cmd) local handle = io.popen(cmd, "r") if handle then local result = handle:read("*a") handle:close() return result end returnnil end
-- Windows localoutput = execute_command("dir") -- Linux/macOS -- local output = execute_command("ls -la")
local file = io.open("data.txt", "r") if file then -- 读取一个数字 local num = file:read("*n") print("数字:", num) -- 读取一行 local line = file:read() print("行:", line) -- 读取 10 个字节 local chunk = file:read(10) print("10 字节:", chunk) file:close() end
localfunctionprocess_large_file(filename) local f = io.open(filename, "r") ifnot f then print("无法打开文件:", filename) return end local line_count = 0 for line in f:lines() do line_count = line_count + 1 -- 处理每一行 -- 这里简单打印行号 if line_count % 1000 == 0then print("已处理行数:", line_count) end end f:close() print("总行数:", line_count) end
localfunctionparse_csv_line(line) local fields = {} local current = "" local in_quotes = false for i = 1, #line do local c = line:sub(i, i) if c == '"'then in_quotes = not in_quotes elseif c == ','andnot in_quotes then table.insert(fields, current) current = "" else current = current .. c end end table.insert(fields, current) return fields end
localfunctionread_csv(filename) local f = io.open(filename, "r") ifnot f thenreturnnilend local data = {} local headers = parse_csv_line(f:read()) for line in f:lines() do local fields = parse_csv_line(line) local record = {} for i, header inipairs(headers) do record[header] = fields[i] end table.insert(data, record) end f:close() return data end
localfunctionwrite_csv(filename, data, headers) local f = io.open(filename, "w") ifnot f thenreturnfalseend -- 写入表头 if headers then f:write(table.concat(headers, ",") .. "\n") end -- 写入数据 for _, record inipairs(data) do local fields = {} for _, header inipairs(headers) do local value = tostring(record[header] or"") -- 如果包含逗号或引号,用引号包裹 if value:find('[,"]') then value = '"' .. value:gsub('"', '""') .. '"' end table.insert(fields, value) end f:write(table.concat(fields, ",") .. "\n") end f:close() returntrue end
14.5 代码加载:dofile / loadfile / load
dofile
直接执行文件中的 Lua 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13
-- 创建一个脚本文件 local f = io.open("greeting.lua", "w") f:write([[ local name = "Lua" print("Hello, " .. name .. "!") return 42 ]]) f:close()
-- 执行文件 local result = dofile("greeting.lua") --> Hello, Lua! print(result) --> 42
loadfile
将文件编译为函数但不执行:
1 2 3 4 5 6 7 8 9 10 11
-- 加载但不执行 local func = loadfile("greeting.lua") if func then -- 执行 local result = func() print(result) --> 42 end
-- 可以多次执行 func() func()
load
从字符串加载 Lua 代码:
1 2 3 4 5 6 7 8 9 10 11 12
-- 编译字符串形式的 Lua 代码 local func = load("return 2 + 2") if func then print(func()) --> 4 end
-- 动态代码执行 local expression = "10 * (5 + 3)" local f = load("return " .. expression) if f then print(f()) --> 80 end
-- 方式一:返回错误(类似 Go 风格) localfunctionread_file_safe(filename) local f = io.open(filename, "r") ifnot f then returnnil, "无法打开文件" end local content = f:read("*a") f:close() return content, nil end
local content, err = read_file_safe("nonexistent.txt") ifnot content then print("读取失败:", err) end
-- 方式二:使用 pcall localfunctionsafe_call(func, ...) local results = {pcall(func, ...)} ifnot results[1] then print("调用失败:", results[2]) returnnil end table.remove(results, 1) returntable.unpack(results) end