This video is part 4 of a series:
This guide provides an overview of common types of Lua modules and best practices for each, building off of the basics described in Organizing Lua Code With Modules.
In general, module tables should not contain any internal state. By separating the module's state from its behavior, the code becomes more modular and independent, allowing for easier testing and debugging. It also allows modules can be more easily shared between projects and reused in different contexts.
Instead, either pass state in as a function parameter or use class instances to hold state.
-- GOOD: a stateless module
local Bank = {}
function Bank.Deposit(account, amount)
return acount.balance = account.balance + amount
end
function Bank.Withdraw(account, amount)
if account.balance < amount then
DCEI.LogError("Insufficient funds")
else
return account.balance - amount
end
end
return Bank
-- BAD: a stateful module
local Bank = {}
local balance = 0
function Bank.Deposit(amount)
return balance = balance + amount
end
function Bank.Withdraw(amount)
if balance < amount then
DCEI.LogError("Insufficient funds")
else
return balance - amount
end
end
return Bank
In Lua, you should use the :
function syntax when defining methods for class instances. This allows you to implicitly pass the instance as the first parameter to the function. Note that class instances are variables that use lower_snake_case
styling.
Meanwhile, you should use the .
function syntax when defining regular functions that don't belong to class instances. Note that modules use PascalCase
styling.