[TIPS & TRICKS] LUA
Prolusion
I want to depict few tips and tricks on LUA which new scripters may/may not know.
Assigning a value which is not nil
I saw most scripters does that using the following code:
local someVar = anotherVar
if someVar == nil then someVar = 10 end
Which can be shortened to this:
local someVar = anotherVar or 10
This is what LUA is doing. It takes the anotherVar, and if it's nil or false it will use the value which is after the or statement.
You can also do it more than once:
local someVar = anotherVar or otherAnotherVar or justSomeVar or 10
The same thing can be done inside a function as well.
Singular Check
This is a nice trick which allows you to make singular checks more efficient than before.
The following code:
local someCondition = "Yes"
local someVar = 5
if someCondition == "Yes" then someVar = 10
else someVar = 0
end
Which can be shortened to this:
local someVar = (someCondition == "Yes") and 10 or 5
This is how LUA understand. If the condition is true(which is someCondition on the example) it will assign the value of someVar to whatever the value is after the and operator and if it's false or nil the value after or operator will be assigned.
Ignore Parenthesis
Yet another simple trick.
The following code:
function doSomething(doWhat)
if type(doWhat) == "string" then print(doWhat) end
end
doSomething("Hey now brown cow.")
Which can also written like this:
function doSomething(doWhat)
if type(doWhat) == "string" then print(doWhat) end
end
doSomething"Hey now brown cow."
When the first and only argument to a function is a string or a table you can ignore the parenthesis.
Named Arguments
Named arguments is a system where a function takes a table of named arguments instead of individual arguments. This allows the function to be called with missing arguments. That's how I define it
Use the following code:
local function someThing(player)
print(player.Name)
print(player.Exp)
print(player.Health)
end
someThing{Name = "Cassandra", Age = 199, Health = 0.5}
Then you can also ignore argument:
someThing{Name = "Cassandra", Health = 0.5}
Instead of:
someFunc("Cassandra", nil, 0.5)
For Loop Optimization
Access to external locals (that is, variables that are local to an enclosing function) is not as fast as access to local variables, but it is still faster than access to globals.
The following code:
for i = 1, 1000000 do
x = x + math.sqrt(i)
end
Can be optimized to:
local squareRoot = math.sqrt
for i = 1, 1000000 do
x = x + squareRoot (i)
end
Object Behavior from OOP
You can use object behavior from Object Oriented Programming inside LUA too using tables.
Consider using this:
AnObject = {};
AnObject.AFunction = function ()
print"I am an object yeppie!"
end
AnObject.AFunction();
--Which call the AFunction inside AnObject class.
Whenever I discover something new, I will attempt to share it here.