lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2011/4/18 Gilles Ganault <gilles.ganault@free.fr>:
> Hello
>
>        I'd like to read a text file into either a string or a a table,
> provided I can iterate through the items it contains.
>
> Both ways end with error "unexpected symbol near 'for'":
>
> ==============
> libs = io.open("dynlibs.txt","r")
> libs = libs:read("*all")
> -- unexpected symbol near 'for'
> for lib in libs do
>        print(lib)
> end
> libs:close()
> ==============
> libs = io.open("dynlibs.txt","r")
> local tlibs = {}
> tlibs=libs:read("*all")
> -- unexpected symbol near 'for'
> for lib in tlibs do
>        print(lib)
> end
> ==============
>
> How do this in Lua?

"for x in t do end" where t is a simple table is not a valid
expression. You have to use iterators, like ipairs and pairs, or
file:lines. For example you an write :

local libs = io.open("dynlibs.txt","r")
for lib in libs:lines() do
       print(lib)
end
libs:close()