Hello. I'm asking this question because I want to learn the basis of compacted conditionals (e.g. m or 17
).
I've been scripting for quite a while, I'm certainly not new at it, but somehow this slipped me by, and I feel like it could give me a chance to write more efficient code.
I've read up on it, and the syntax confuses me, and I've been on Scripting Helpers for a while only answering questions, so I figured I'd ask here.
Anyway, my question is, what is the syntax of a conditional that is simply put; an example-
a or b c or d m not 666
... and when exactly would be the most efficient time/place in code to do it?
Thanks for reading; all replies are appreciated!
It's useful when you want to do a little logic statement, but don't feel like having an additional scope for that. The syntax is simply like that, just like you wrote. So here is a little example:
local a = false local b = 123 c = a or b -- 'c' would end up as 123, because 'a' is false, so it'd check b m = c or d -- same as before d = m ~= 666 or m -- 'd' would be 123, because it wasn't equal to 666 so I choose for it to be the old value instead
Have you read my blog post? https://scriptinghelpers.org/blog/two-scripting-tips-which-will-make-scripting-easier
I normally use those to script if-then blocks. What's really handy to note is that Lua handles everything as true except false and nil. You can use this!
function get(tab, provided) local to_index = provided or 1 -- if provided is not available, return 1 return tab[to_index] end
Also, the syntax you use is incorrect. You should try to think of "or", "and" and "not" as functions.
I will rewrite those without using and/or/not:
function OR(arg1, arg2) -- equivalent of arg1 or arg2 if arg1 == nil then return arg2 elseif arg1 == false then return arg2 end return arg1 end function AND(arg1, arg2) equivalent of arg1 and arg2 if arg1 == nil then return arg1 elseif arg1 == false then return arg1 end return arg2 end function NOT(arg1) -- equivalent of arg1 if arg1 == nil then return true elseif arg1 == false then return true end return false end
There are two differences with these functions though. These statements only evaluate when necessary. For example, torso = Player.Character and Player.Character:FindFirstChild("Torso")
only calls :FindFirstChild if Player.Character is not nil or false. In that case, this statement never errors (well, unless Player is not a table/instance or Player is a table and the Character field is present and Player.Character does not have a function called FindFirstChild - but those errors are not likely to happen).
The other difference is that you can just call a function: 'a()' is a valid statement if a
is a function. a or b
is not a valid statement though, you need to do something with it:
a = a or b
z = d and c
b = not r
Those statements are valid.