Home

dofile

Dofile is a function in Lua's standard libraries that loads and executes a Lua source file. It reads the contents of the given file, compiles them into a chunk, and runs that chunk immediately. The function returns any values produced by the chunk’s return statement, or the last expression if there is no explicit return; if the chunk does not return a value, dofile yields no return value.

Signature and behavior: dofile([filename]) takes an optional filename. When a filename is provided, dofile searches for

Environment and side effects: The executed chunk runs in the same global environment as the caller, so

Relation to loadfile and require: Dofile internally uses the mechanism of loadfile to obtain a chunk and

Usage considerations: Common uses include running configuration or script files at runtime and reusing code without

and
opens
that
file
to
load
and
run
it.
If
filename
is
nil
or
omitted,
dofile
reads
a
chunk
from
the
standard
input.
If
the
file
cannot
be
opened
or
the
chunk
contains
an
error,
dofile
raises
an
error
rather
than
returning
a
value.
it
can
read
and
modify
global
variables
and
functions.
dofile
does
not
create
or
modify
module-specific
environments,
and
it
does
not
cache
the
loaded
file
for
future
calls,
unlike
the
require
function.
then
executes
it.
Unlike
require,
dofile
does
not
insert
the
module
into
package.loaded,
and
it
does
not
perform
the
module
search
path
caching
or
versioning.
If
you
need
to
inspect
or
control
the
chunk
before
execution,
you
can
use
loadfile
and
then
call
the
resulting
function,
possibly
within
an
error-protected
wrapper.
creating
a
formal
module.
Because
dofile
executes
arbitrary
code,
it
should
be
used
only
with
trusted,
verified
files.