So, Lets say I’m trying to make my own DataStore type System, I want it to Save whatever I need it to, and to do it efficiently without suffering many Problems to it, Here I am trying to load Data by using GetAsync
, using OOP (Object Oriented Programming), which wrapped in a pcall
, should look like this:
local success, result = pcall(DataStore.GetAsync, DataStore, self.Key)
-- success is the variable that will tell us if the operation was successful
-- result for this usage will give us the Following Data:
--- Success Responses:
--/ 1: Data from the Specified Key
--/ 2: No data from the Specified Key (Simplified: nil )
--- Error Responses:
--/ 1: Error
This works as Intended, There is nothing wrong with the way its formatted, and we can Handle the Errors Properly, if you were thinking normally, you would probably do the following, which is a very common way that people do it, or teach you how to do it:
if success then -- if the operation was successful
if result then -- if there is Data
print("Data Loaded")
return result
else -- if there is no Data
warn("No Data Found")
return StarterData
end
else -- if the operation Failed
warn("DataStore Failed to Load")
end
As you can see, its pretty normal, should work as intended, but it can be further simplfied with the usage of the keywords and
, and or
, without the If statement they work slightly differently, and can be used for many Different Purposes, they are very useful, and tend to have your code look shorter.
Another thing we can do is to use a Boolean, the if
statements will check if something is true, so with the usage of and
, and or
, we can check.
But then we are able to format our code like this because of how Lua’s Syntax works:
--- Method 1:
local Data = success and result and result or StarterData
-- if success is true and result is true then result
-- otherwise you will get Starter Data
--- Method 2:
local Boolean (result ~= nil)
-- Boolean will return a Boolean depeding if the current statement is true or not
-- if its nil or false, its false, otherwise its true
local Data = Boolean and result or StarterData
-- if the Boolean is true then it would be our Data
-- otherwise its replaced by StarterData
--- Method 3:
result = result or StarterData
-- if result is true then it will be itself
-- otherwise it will be replaced with StarterData
Which shortens the code by a little bit.
But this isnt some Tutorial, and Sorry if I make it look like one, I’m just here to ask about the Efficiency of the Following codes, and whether they are better to use or not.
While these may be shorter than the other, it may not make them faster, so what would be better to use?