1

so I have to write a function join(a,b,c,d) that takes up to 4 strings, and joins them together with a comma. The function should still work when given less than 4 strings, including printing out just one string with no commas attached when given only one string as an argument. However, I can only make it work with 3

function join(a,b,c,d)
    if b == nil then
      print(a .. ", " .. c .. ", " .. d) 
    elseif c == nil then
        print(a .. ", " .. b .. ", " .. d) 
    elseif d == nil then
        print(a .. ", " .. b .. ", " .. c) 
    else
        print(a .. ", ".. b .. ", " .. c .. ", " .. d) 
    end
end

I don't know how to make it take less than 3 arguments, please help

2 Answers2

5

If you only concatenate and print those string inputs, you don't even need to give names to arguments:

local function join(...)
    print(table.concat({...}, ", ")
end

join("a")
join("a","b")
join("a","b","c")
join("a","b","c","d","e","f","blah-blah","as many as you want", "even more")
Vlad
  • 5,450
  • 1
  • 12
  • 19
2

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:

  1. 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.
  2. 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.
HirdayGupta
  • 408
  • 4
  • 16