Log In  

Hi geeks !

I would like display in my game this message for some tests :

test : true

but "test" is a boolean variable. I can display with a classical variable with :

print("x:"..pix.x,10,10,10)

x: 22

but with a boolean variable no :

print("test:"..test,10,4,8)

I have an error :

runtime error
<eof>
line 106: attempt to concatenate local 'test' (a boolean value)

Thank in advance for your help :)

P#33625 2016-12-18 05:33 ( Edited 2016-12-19 09:34)

1

easiest way:

print("test:"..(test and 'true' or 'false'),10,4,8)
P#33628 2016-12-18 07:11 ( Edited 2016-12-18 12:11)

Thanks for you, it work!
But I don't understand this logic, we can put a conditions in print ()?
How this instruction work it ?

P#33635 2016-12-18 10:50 ( Edited 2016-12-18 15:50)
1

you can put anything in print() as long as it evaluates to a printable value.

  • (a and b) returns a if a is false or nil, b otherwise (whatever b is)
  • (a or b) returns b if a is false or nil (whatever b is), a otherwise (whatever a is)
  • operator and has precedence over operator or

so here's how the evaluation goes:
(true and '1' or '0') -> ((true and '1') or '0') -> '1' or '0' ->'1'
(false and '1' or '0') -> ((false and '1') or '0') -> false or '0' ->'0'

this syntax (a and b or c) is the lua version of the conditional ternary operator (3 operands).
that's very handy once you know it :)

more info here:http://www.lua.org/manual/5.0/manual.html (2.5.3 – Logical Operators)
and there:http://lua-users.org/wiki/TernaryOperator

P#33642 2016-12-18 12:42 ( Edited 2016-12-18 17:45)

Thank you very very much for your explanations !
Have you a game in dev ?

P#33672 2016-12-19 04:34 ( Edited 2016-12-19 09:34)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-28 16:53:05 | 0.006s | Q:18