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!
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.
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.
Lua uses nil as a kind of non-value, to represent the absence of a useful value.
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.
I'd do this:
function iffunc(k,str,str1)
if k == 0 then return "" end
return str .. k .. (str1 or "")
end
You should add an else
statement in the function, where you return an empty string (""
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With