Zercon
Zercon

Reputation: 135

What does local _, x = ... do in lua?

I'm looking at some lua code on github which consists of many folders and files. Next to external libraries, each file starts with:

local _,x = ...

Now my question is, what is the purpose of this, namely the 3 dots? is it a way to 'import' the global values of x? In what way is it best used?

Upvotes: 2

Views: 692

Answers (2)

shingo
shingo

Reputation: 27011

They are arguments from the command line.

Read lua's reference manual, in the chapter Lua Standalone, it says:

...If there is a script, the script is called with arguments arg[1], ···, arg[#arg]. Like all chunks in Lua, the script is compiled as a vararg function.

For example if your lua script is run with the command line:

lua my_script.lua 10 20

In my_script.lua you have:

local _, x = ...

Then _ = "10" and x = "20"


Update when a library script is required by another script, the meaning of the 3 dots changes, they are arguments passed from the require function to the searcher:

Once a loader is found, require calls the loader with two arguments: modname and an extra value, a loader data, also returned by the searcher.

And under package.searchers:

All searchers except the first one (preload) return as the extra value the file name where the module was found

For example if you have a lua file that requires my_script.lua.

require('my_script')

At this time _ = "my_script" and x = "/full/path/to/my_script.lua"

Note that in lua 5.1, require passes only 1 argument to the loader, so x is nil.

Upvotes: 2

... is the variable arguments to the current function.

E.g.:

function test(x, y, ...)
    print("x is",x)
    print("y is",y)
    print("... is", ...)

    local a,b,c,d = ...
    print("b is",b)
    print("c is",c)
end
test(1,2,"oat","meal")

prints:

x is 1
y is 2
... is oat meal
b is meal
c is nil

Files are also treated as functions. In Lua, when you, or someone else, loads a file (with load or loadfile or whatever), it returns a function, and then to run the code, you call the function. And when you call the function, you can pass arguments. And none of the arguments have names, but the file can read them with ...

Upvotes: 4

Related Questions