Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 721
Josh Avatar asked Nov 08 '11 11:11

Josh


People also ask

How do I concatenate in Lua?

The most straightforward way to concatenate (or combine) strings in Lua is to use the dedicated string concatenation operator, which is two periods ( .. ). message = "Hello, " .. "world!" -- message equals "Hello, World!" Numbers are coerced to strings. For fine-grained control over number formatting, use string.

Is nil null Lua?

When programming in Lua, it is important to understand the different meanings of nil and NULL. Nil is the "unknown type" in the context of Lua whereas null and NULL represent the SQL NULL. The NULL constant is not part of standard Lua and was added by us so the user can do NULL comparisons of result data.

Why does Lua use nil instead of null?

Lua uses nil as a kind of non-value, to represent the absence of a useful value.

What is a nil value in Lua?

In Lua, nil is used to represent non-existence or nothingness. It's frequently used to remove a value in a table or destroy a variable in a script.


2 Answers

I'd do this:

function iffunc(k,str,str1)
  if k == 0 then return "" end
  return str .. k .. (str1 or "")
end
like image 105
kikito Avatar answered Oct 21 '22 22:10

kikito


You should add an else statement in the function, where you return an empty string ("").

like image 37
Some programmer dude Avatar answered Oct 21 '22 22:10

Some programmer dude