2012-06-26 38 views
17

tôi đã tự hỏi nếu có một cách để đọc dữ liệu từ một tập tin hoặc có thể chỉ để xem nếu nó tồn tại và trả về một true hoặc falseLàm thế nào để đọc dữ liệu từ một tập tin trong Lua

function fileRead(Path,LineNumber) 
    --..Code... 
    return Data 
end 
+0

http://stackoverflow.com/questions/4990990/lua-check-if-a-file-exists hoặc http://stackoverflow.com/questions/5094417/how-do-i-read- cho đến khi kết thúc-of-file –

Trả lời

34

Hãy thử điều này:

-- http://lua-users.org/wiki/FileInputOutput 

-- see if the file exists 
function file_exists(file) 
    local f = io.open(file, "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(file) do 
    lines[#lines + 1] = line 
    end 
    return lines 
end 

-- tests the functions above 
local file = 'test.lua' 
local lines = lines_from(file) 

-- print all line numbers and their contents 
for k,v in pairs(lines) do 
    print('line[' .. k .. ']', v) 
end 
2

Có một I/O library có sẵn, nhưng nếu nó có sẵn phụ thuộc vào máy chủ lưu trữ kịch bản của bạn (giả sử bạn đã nhúng lua ở đâu đó). Nó có sẵn, nếu bạn đang sử dụng phiên bản dòng lệnh. Các complete I/O model là rất có thể những gì bạn đang tìm kiếm.

+0

Nếu nó sẽ là một trò chơi, tôi muốn thêm chức năng wrapper của riêng bạn có thể được gọi từ Lua. Nếu không, bạn sẽ mở ra một thùng sâu, bằng cách cấp cho mọi người khả năng xoay đĩa cứng của người chơi khác thông qua addons/maps/plugins. – Mario

4

Bạn nên sử dụng I/O Library nơi bạn có thể tìm thấy tất cả các chức năng tại bàn io và sau đó sử dụng file:read để có được nội dung file.

local open = io.open 

local function read_file(path) 
    local file = open(path, "rb") -- r read mode and b binary mode 
    if not file then return nil end 
    local content = file:read "*a" -- *a or *all reads the whole file 
    file:close() 
    return content 
end 

local fileContent = read_file("foo.html"); 
print (fileContent); 
1

Chỉ cần thêm một chút nếu bạn muốn phân tích cú pháp dòng tệp văn bản được phân cách bằng dấu cách.

read_file = function (path) 
local file = io.open(path, "rb") 
if not file then return nil end 

local lines = {} 

for line in io.lines(path) do 
    local words = {} 
    for word in line:gmatch("%w+") do 
     table.insert(words, word) 
    end  
    table.insert(lines, words) 
end 

file:close() 
return lines; 
end 
Các vấn đề liên quan