luaconcatenationnull

Lua: Is there a way to concatenate "nil" values?


I have the following function in Lua:

function iffunc(k,str,str1)
  if k ~= 0 then
    return str .. k .. (str1 or "")
  end
end

This function allows me to check if value k is populated or not. I'm actually using it to determine if I want to display something that has zero value. My problem is this: I'm trying to concatenate a string of iffunc(), but since some of the values are 0, it returns an error of trying to concatenate a nil value. For instance:

levellbon = iffunc(levellrep["BonusStr"],"@wStr@r{@x111","@r}") .. iffunc(levellrep["BonusInt"],"@wInt@r{@x111","@r}") .. iffunc(levellrep["BonusWis"],"@wWis@r{@x111","@r}")

If any of the table values are 0, it'll return the error. I could easily put 'return 0' in the iffunc itself; however, I don't want a string of 000, either. So how can I work it where no matter which values are nil, I won't get that error? Ultimately, I'm going to do an iffunc on the levellbon variable to see if that's populated or not, but I've got that part figured out. I just need to get past this little hurdle right now. Thanks!


Solution

  • I'd do this:

    function iffunc(k,str,str1)
      if k == 0 then return "" end
      return str .. k .. (str1 or "")
    end