Main Content

Dot, dot, dot in Lua - variable length parameter lists

Archive - Originally posted on "The Horse's Mouth" - 2009-08-11 06:38:48 - Graham Ellis

Lua functions can take any number of parameters - the ... (dot,dot,dot) table given as a parameter 'soaking up' all remaining parameters into the indexed section of the table, rather this "*" in front of a parameter in PHP. (In Perl, the whole list appears in @_)

function join (sep,...)
togo = {...}


There are two styles to calling Lua functions - passing in a comma separated list of parameters in round brackets, or combining them into a table in curly braces:

-- Many parameter variety
str1 = join(" ","This","is","a","Program")
-- Two parameter variety
str2 = join(" ",{"This","is","another","Program"})


And the code within the function can tell the styles apart and adapt itself as appropriate by checking the number and/or type of parameters:

if type(togo[1]) == "table" then

See source code of full example


Illustration - delegates on a private Lua course. We run public Lua training courses at our centre in Melksham, Wiltshire, England and private course onsite worldwide.