What you're looking for can be achieved by what most programming languages call "default/optional parameters." However, Lua seems to do this slightly differently - it only actually requires the argument if you actually use it in the function (without surrounding it with the conditional checking for nil) - so your approach was actually correct, just missing a little conditional magic. Rewrite your program as follows, you'll find that the function does what you need:
function join(a,b,c,d)
io.write(a)
if b ~= nil then
io.write(", " .. b)
end
if c ~= nil then
io.write(", " .. c)
end
if d ~= nil then
io.write(", " .. d)
end
end
join('test')
join('test', 'test1')
join('test', 'test1', 'test2')
join('test', 'test1', 'test2', 'test3')
Test-run the code here: https://jdoodle.com/a/qoc
Important note about the change from your version: notice how it's just if-blocks and not if-else blocks. That is primarily what enables the "flow-of-control" to check for potentially none of the last 3 params existing. You might want to do some further reading on "flow-of-control" and "conditionals."
Note: replaced print
with io.write
because:
io.write
doesn't append a newline character to the end of its output by default, so you can print out your words on the same line, separated only by a comma and a space.
- For future reference: as the discussions in these answers indicate, io.write is the preferred output method anyway.
Further reference:
- Check out this discussion about "default/optional arguments" and their lua equivalents. Since you didn't actually have any "default" values, so to speak, for your optional params, it was good enough to simply check their nil conditions. Often, you may want to use a "default" value though, and that discussion goes into details on how to do so in Lua.