Load, loadfile and loadstring needs explanation

I would like to ask you for a straight-forward explanation of the above functions. Especially what is “chunk” or “Lua chunk” and how should I understand it? Like inline functions? Or calls? How and when should I use each function (except the type of source, obviously)? Can I store loaded chunks in a variable and then call it at will by calling this variable()? Also what is the difference between dofile and loadfile? I am asking like a newbie, I know, but I’m kind of misunderstanding some basic concepts and afraid to use them. And it could be useful for others in the future too :wink:

1 Like

The Lua manual to the rescue:

https://www.lua.org/pil/1.1.html

“Each piece of code that Lua executes, such as a file or a single line in interactive mode, is a chunk. More specifically, a chunk is simply a sequence of statements.”

From the Lua manual:

dofile ([filename])

Opens the named file and executes its contents as a Lua chunk.

load (func [, chunkname])

Loads a chunk using function func to get its pieces. Each call to func must return a string that concatenates with previous results. A return of an empty string, nil, or no value signals the end of the chunk. If there are no errors, returns the compiled chunk as a function.

loadfile ([filename])

Similar to load, but gets the chunk from file filename

loadstring (string [, chunkname])

Similar to load, but gets the chunk from the given string.


So dofile will load and immediately execute the file. The load functions will load a bunch of Lua code but not execute it and instead return a function that can be invoked to run the code.

3 Likes

I have a question, if i have a entire script lua compiled (luac) and load dont work, how should i do?

Do you really need to compile it beforehand? Can’t you just load it using one of the methods described above?