This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Nolorwolf's profile picture

[lua] Explanation of a line

Started by Nolorwolf, 04 January 2013 - 03:12 AM
Nolorwolf #1
Posted 04 January 2013 - 04:12 AM
I have received a code yesterday as a response containing a line


write((#tostring(i) == 1 and ('0'..i) or i) .. " " .. (i == 1 and "second" or "seconds"))

It is supposed to add 0 in front of one digit numbers while counting down.
I understand last part, but I don't get how


write((#tostring(i) == 1 and ('0'..i) or i)

recognizes if its one or two digit number?

Thx :)/>
Kingdaro #2
Posted 04 January 2013 - 04:27 AM
So in this example, I'm assuming said number is i.

If i is 5, the tostring() conversion of that is "5". It then finds the length of "5" using the # operator. It then uses a special statement:

<condition> and <if true=""> or <if false="">

It checks if <condition> is true, and returns <if true=""> if it's true, and <if false=""> if it's false. It checks if the length of "5" is 1, and if so, add a 0. Otherwise, just return the number without adding zeroes.</if></if></condition></if></if></condition>
Lyqyd #3
Posted 04 January 2013 - 04:28 AM
This is using Lua's handling of and and or to create a ternary operation. The first bit is, "if the length of the string form of the number i is one", and if this is true, it evaluates the expression on the other side of the and, which is a string with the 0 prepended. Since Lua returns whatever the value is, that is what would get printed. If the length was not 1, it would skip evaluating the expression to the right of the and (since the first expression of the and was false, the whole and is false) and go straight to evaluating the expression to the right of the or, which returns the number itself. The general ternary form for Lua can be written thus:

<condition> and <valueIfTrue> or <valueIfFalse>
Nolorwolf #4
Posted 04 January 2013 - 04:35 AM
Ahh, so basically #tostring(nn) gives a length of 2, and #tostring(n) a length of 1 and automatically gives it as a number for comparison? Does it work with #(i) if it is already a string?
That's the part I was confused about :)/>
Lyqyd #5
Posted 04 January 2013 - 04:41 AM
Yes, if i were already a string, #i would give the length of i.

Edit: though, #tostring(nn) wouldn't necessarily give a length of 2, unless the variable "nn" happened to contain a two-letter string or two-digit number. I'm assuming you meant it as a literal two-digit number; I simply wanted to clarify for future readers.
Kingdaro #6
Posted 04 January 2013 - 04:42 AM
Nah, just tested. Lua doesn't like it when you try to use # on a number.
Nolorwolf #7
Posted 04 January 2013 - 04:48 AM
Ok, thx, that clarifies things a lot, and yea nn was meant to be a 2 digit number :)/>