Reputation: 12468
Okay so I am new to the Lua language so this could be a super stupid question, but I have come across the following statement and I have no idea what it means (even after some searching)
if (...) then
-- Doing some stuff
end
What does the ...
mean?
Upvotes: 4
Views: 255
Reputation: 122493
...
is used in the function parameter to indicate that the function is variadic. It can be used inside the function as an expression, representation the function's extra arguments.
For instance, this function takes a fixed argument plus variable arguments:
function vafun(num, ...)
if (...) then
for _, v in ipairs{...} do
print(v)
end
else
print("empty var")
end
end
The if(...)
tests if the variable arguments part is empty.
vafun(3, 4, 5)
vafun(3)
vafun()
Output:
4
5
empty var
empty var
Upvotes: 1
Reputation: 48659
...
is used in vararg functions. Its value is a list of all the "extra" arguments (i.e. those that follow the last named argument of the current function.)
(...)
(like any other expression in parentheses) adjusts the result to one value (the first one in the list.)
So that if
statement effectively means "if the first variadic argument exists and is not false
or nil
."
Examples:
local function f1(...)
if (...) then
return true
else
return false
end
end
local function f2(x, ...)
if (...) then
return true
else
return false
end
end
print(f1()) -- false
print(f1(1)) -- true
print(f1(1, 2)) -- true
print(f1(1, nil)) -- true
print(f1(nil, 2)) -- false
print(f2()) -- false
print(f2(1)) -- false
print(f2(1, 2)) -- true
print(f2(1, nil)) -- false
print(f2(nil, 2)) -- true
At the top level (i.e. not inside a function . . . end
form) it still works the same way, but the current function is a chunk (i.e. script or module.)
If it is a module, (...)
gives the module name. But then the if(...)
test would not be useful because the first argument is always a string.
If it's a script, (...)
gives the first command-line argument (and the if(...)
tests whether any arguments were given.)
Upvotes: 3