Condiciones inline en Lua (a == b? "sí": "no")?


¿Hay que usar condiciones inline en Lua?

Tales como:

print("blah: " .. (a == true ? "blah" : "nahblah"))
Author: RBerteig, 2011-04-03

3 answers

Claro:

print("blah: " .. (a and "blah" or "nahblah"))
 86
Author: John Zwinck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-02 20:59:39

Si el a and t or f no funciona para usted, siempre puede crear una función:

function ternary ( cond , T , F )
    if cond then return T else return F end
end

print("blah: " .. ternary(a == true ,"blah" ,"nahblah"))

Por supuesto, entonces usted tiene el retroceso que T y F siempre se evalúan.... para moverse que necesita para proporcionar funciones a su función ternaria, y que puede ser difícil de manejar:

function ternary ( cond , T , F , ...)
    if cond then return T(...) else return F(...) end
end

print("blah: " .. ternary(a == true ,function() return "blah" end ,function() return "nahblah" end))
 16
Author: daurnimator,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-03 12:29:48

Hay un buen artículo en lua-users wiki sobre ternary operator, junto con la explicación del problema y varias soluciones.

 11
Author: Marcin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-03 05:42:07