lua-users home
lua-l archive

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


On Sat, Oct 26, 2013 at 9:52 PM, Lorenzo Donati
<lorenzodonatibz@tiscali.it> wrote:

> Yep! fscanf is a nasty beast. I assume it is used in Lua codebase to
> keep the LOC count down, but I wonder whether it would be better to
> avoid it completely and implement "*n" using a custom parsing routine.

IMNSHO parsing numbers directly from a file is a hairy problem, what
do ayou want to do when reading "123E+X", you could reasonably read
123 and leve out E+X, error out and leave ... all? X ( which is the
position of the first bad char ) E+X?

Even the line reading formats are underspecified in the manual:

This is really difficult to specify correctly
  "*n": reads a number; this is the only format that returns a number
instead of a string.

This is the easiest, few things to comment on it
"*a": reads the whole file, starting at the current position. On end
of file, it returns the empty string.

These couple are a little bit underspecified.
  "*l": reads the next line skipping the end of line, returning nil on
end of file. This is the default format.
  "*L": reads the next line keeping the end of line (if present),
returning nil on end of file.
What happens with *L when last line of the file is not NL terminated?
it hints it will return a non-newline terminated, and looking at
liolib.c seems to confirm it, but a little longer explanation would be
nice, something along the lines 'if a non-empty file does not end with
a newline ( for which it must have a non-empty last line ) both *l and
*L will return the same last line.

IMO the best form to reuse the parser will be to have a %N with a
convenient N, which matches a number in string.match, so it will be
easy for people to read full lines and match them. This is what I've
ended up doing in every program I've made ( not only in lua ) which
needs to read unchecked input.

Also, reading numbers from a file ( even with fscanf ) is normally
only useful when you only have numbers in it, as soon as you mix them
with strings the things became difficult.

Francisco Olarte.