Content deleted Content added
m convert special characters found by Wikipedia:Typo Team/moss (via WP:JWB) |
added information about Lua's vararg system in examples |
||
Line 221:
console.log(sum(3, 2)); // 5
console.log(sum()); // 0
</syntaxhighlight>
=== In [[Lua (programming language)|Lua]] ===
[[Lua (programming language)|Lua]] functions may pass varargs to other functions the same way as other values using the {{Code|return}} keyword. tables can be passed into variadic functions by using, in Lua version 5.2 or higher<ref>{{Cite web |title=Lua 5.2 Reference Manual |url=https://www.lua.org/manual/5.2/manual.html#pdf-table.unpack |access-date=2023-02-05 |website=www.lua.org}}</ref> {{Code|table.unpack}}, or Lua 5.1 or lower<ref>{{Cite web |title=Lua 5.1 Reference Manual |url=https://www.lua.org/manual/5.1/manual.html#pdf-unpack |access-date=2023-02-05 |website=www.lua.org}}</ref> {{Code|unpack}}. Varargs can be used as a table by constructing a table with the vararg as a value.<syntaxhighlight lang="lua">
function sum(...) --... designates varargs
local sum=0
for _,v in pairs({...}) do --creating a table with a varargs is the same as creating one with standard values
sum=sum+v
end
return sum
end
values={1,2,3,4}
sum(5,table.unpack(values)) --returns 15. table.unpack should go after any other arguments, otherwise not all values will be passed into the function.
function add5(...)
return ...+5 --this is incorrect usage of varargs, and will only return the first value provided
end
entries={}
function process_entries()
local processed={}
for i,v in pairs(entries) do
processed[i]=v --placeholder processing code
end
return table.unpack(processed) --returns all entries in a way that can be used as a vararg
end
print(process_entries()) --the print function takes all varargs and writes them to stdout separated by newlines
</syntaxhighlight>
|