2012-06-26 19 views
17

mi chiedevo se ci fosse un modo per leggere i dati da un file o forse solo per vedere se esiste e restituire un true o falseCome leggere i dati da un file in Lua

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

http://stackoverflow.com/questions/4990990/lua-check-if-a-file-exists o http://stackoverflow.com/questions/5094417/how-do-i-read- fino alla fine del file –

risposta

34

Prova questo:

-- 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'è una I/O library disponibile, ma se è disponibile dipende dall'host di scripting (supponendo di aver incorporato lua da qualche parte). È disponibile, se stai usando la versione da riga di comando. Il complete I/O model è molto probabilmente quello che stai cercando.

+0

Se si tratta di un gioco, preferirei aggiungere la propria funzione wrapper che può essere chiamata da Lua. Altrimenti si aprirà una lattina di worm, garantendo alle persone la possibilità di rovinare gli hard disk di altri giocatori tramite addon/mappe/plug-in. – Mario

4

si dovrebbe usare il I/O Library dove si possono trovare tutte le funzioni al tavolo io e quindi utilizzare file:read per ottenere il contenuto del 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

Solo un po 'più se si vuole analizzare uno spazio separato da riga di file di testo per riga.

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 
Problemi correlati