Best Practices

From Avorion Wiki
Jump to: navigation, search

Use Namespaces[edit | edit source]

In order to save memory and ease access of scripts between each other, you should use namespaces. Note that namespaces should be used mainly for scripts that are supposed to remain on scriptable objects for a long time. Scripts like missions that are attached to the player for a limited time and then cleaned up again, can remain without a namespace to make it easier for the game to clean them up again.

Working together with other Mods[edit | edit source]

To access other mods' meta data, use the Mods() function. You can find more details the Mods() function in the Scripting API.

Use include()[edit | edit source]

Avorion brings its own variant of require(): include(), which should be used instead of require() since it can load mod extensions as well. For more information check out this guide on modifying modules and libraries and why you should use include().

Compatibility with other Versions[edit | edit source]

In order to achieve good compatibility between mods, use the Mods() call to gather information about other enabled mods and their version.

Use GameVersion() calls to get the current Avorion version and maybe adjust your mod code to API changes that might have happened between updates.

Avoid locals in onServer() / onClient() blocks[edit | edit source]

Avoid constructs like

if onServer() then
local myVar = 15 -- some value
end

If another mod wants to access your mod, it won't have access to myVar, since that variable is only visible inside the if onServer() then block.

Note: This behavior can be used on purpose to restrict access to some local variables. But keep in mind that other mods can still very much access your mod and potentially undo and access everything it does anyways, so comment on your code why you're restricting access.

Avoid top-level returns[edit | edit source]

if onServer() then return end 

-- this stuff is supposed to run only on the client
local myVar = 15 -- some value

A script like this is not extendable if the if clause isn't met.

Avoid conditional return of modules[edit | edit source]

-- BAD
local Module = {}

function Module.concat(a, b)
    return a .. " - " .. b
end 

if onServer() then 
    return Module 
else 
    return {} 
end 
-- << extensions will be added here - AFTER the returns! >>
-- GOOD
local Module = {}

function Module.concat(a, b)
    return a .. " - " .. b
end 

if onServer() then 
    Module = {}
end 
-- << extensions will be added here - BEFORE the return! >>
return Module

When Avorion does its extension injection inside the require() call, it looks for a single return statement at the bottom of the file, to distinguish it from a non-module file. The above code doesn't have that and thus won't be recognized as a module, meaning extensions to the file will be placed after the return statement, which is not what you want in a module file.

See Also[edit | edit source]