Lua: Is there a way to concatenate "nil" values?
Solution 1
I'd do this:
function iffunc(k,str,str1)
if k == 0 then return "" end
return str .. k .. (str1 or "")
end
Solution 2
You should add an else
statement in the function, where you return an empty string (""
).
Josh
Updated on November 13, 2020Comments
-
Josh over 3 years
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!
-
Some programmer dude over 12 yearsCant you just return an empty string (
""
) whenk
is 0? -
Josh over 12 yearsD'oh! I can't believe it was that simple. I blame it on the hour of coding and lack of sleep. Thanks! Just have to modify the function a bit now.
-
Deco over 12 yearsJust so you know in future, you can do this:
something and A or B
. Ifsomething
evaluates to true it will push the value A, otherwise it will push the value B. Example:k ~= 0 and str..k..(str1 or "") or ""
-
ponzao over 12 years@JoachimPileborg You should definitely add that as a proper answer.
-
buch11 almost 4 yearsSelected answer works fine, however this also seems to be working fine for me : print("this is a string " .. tostring(nilObject)) Above line prints output : this is a string nil
-
-
Tw Bert over 6 yearsJust a remark, if you do have a reason to concatenate a nil value, you can do:
'hi' .. string.char(0x00) .. 'there'
.