2012-06-26 10 views
17

Me preguntaba si había una manera de leer los datos de un archivo o tal vez sólo para ver si existe y devuelve un true o falseCómo leer datos de un archivo en 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- until-the-end-of-file –

Respuesta

34

Prueba esto:

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

Hay una I/O library disponible, pero si está disponible depende de su servidor de secuencias de comandos (suponiendo que haya incrustado lua en algún lugar). Está disponible, si estás usando la versión de línea de comando. Es probable que complete I/O model sea lo que estás buscando.

+0

Si va a ser un juego, prefiero agregar su propia función de contenedor que se puede llamar desde Lua. De lo contrario, estás abriendo una lata de gusanos, otorgando a las personas la posibilidad de arruinar los discos duros de otros jugadores a través de complementos/mapas/complementos. – Mario

4

Se debe utilizar la I/O Library donde se pueden encontrar todas las funciones de la mesa io y luego usar file:read para obtener el contenido del archivo.

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 una pequeña adición si uno quiere analizar un espacio separado archivo de texto línea por línea.

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 
Cuestiones relacionadas