Lua: ¿Hay alguna forma de concatenar valores "nulos"?

I have the following function in Lua:

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

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!

preguntado el 08 de noviembre de 11 a las 11:11

Cant you just return an empty string ("") cuando k es 0? -

D'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. -

Just so you know in future, you can do this: something and A or B. Si something 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 "" -

@JoachimPileborg You should definitely add that as a proper answer. -

Selected 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 -

2 Respuestas

Haría esto:

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

respondido 08 nov., 11:18

Just a remark, if you do have a reason to concatenate a nil value, you can do: 'hi' .. string.char(0x00) .. 'there'. - Tw Bert

Deberías agregar un else statement in the function, where you return an empty string ("").

respondido 08 nov., 11:17

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.