2679 posts
Location
You will never find me, muhahahahahaha
Posted 16 March 2015 - 05:07 PM
I have looked at various programs and I have come accross this syntax:
write = term and term.write
What does this syntax do?
Thanks in advance and I hope you can help me.
~Creator
1023 posts
Posted 16 March 2015 - 05:10 PM
That is just a shorter method of using a if then statement to check to see if the term api exists, and then assigning the variable write to term.write.
113 posts
Location
This page
Posted 16 March 2015 - 05:15 PM
Looks to me like they are checking if term exists and if it does set write to term.write.
To go a little more in-depth, when using 'and' if both statements before and after it are not nil or false, it will return what is on the right side of the 'and'
It would be just like
if term then
write=term.write
end
the reason they would not simply do write=term.write is because if term is not a table then trying to access term.write would throw back an error.(however it should be write = type(term)=="table" and term.write, however if term does exist it should be a table, unless someone redefined it.
1426 posts
Location
Does anyone put something serious here?
Posted 16 March 2015 - 05:18 PM
Just some fun trivia here:
This is a useful way of implementing default values to functions. It is worth noting that if false is passed then 123 will be used, so this doesn't work for booleans.
a = a or 123
a = condition and something or another
is similar C's
a = condition ? something : another
If
something is nil or false it will break
Javascript has similar functionality with || and &&.
Edited on 16 March 2015 - 04:20 PM
808 posts
Posted 16 March 2015 - 05:27 PM
Yea so in detail, the
and and
or operators will return either the operand on the left or the one on the right, depending on the operation.
- a and b
The and operator first evaluates a. If a is false or nil, and returns a. Otherwise, and returns b.
- a or b
The or operator first evaluates a. If a is NOT false or nil, or returns a. Otherwise, or returns b.
2679 posts
Location
You will never find me, muhahahahahaha
Posted 16 March 2015 - 06:18 PM
Thans a lot guys ;)/>