Lua Functions
Basic idioms
make a global function myFunction that prints the argument it's called with, and it's type
function myFunction(var) print(var,type(var)) end myfunc = function(var) print(var,type(var)) end
Changing Existing Functions
(-)The bad ways: Overwrite with same file in your mod or completely replacing functions are generally not recommended. (bad) overwrite, set a new function in place of the vanilla function
ISBaseTimedAction.new = function(self, character) --do stuff end
the usual accepted way is to make a new function that calls the prev function that was assigned, *also knows as: hook, wrap, patch, add on to
local original = ISBaseTimedAction.new ISBaseTimedAction.new = function(self, character) --do stuff before local o = original(self, character) --do stuff after return o end
the conditional switch between the original and a custom function
local original = ISBaseTimedAction.new ISBaseTimedAction.new = function(self, character) if matchesConditions then --do custom stuff else return original(self, character) end end
safe calls and result returning
local original = ISBaseTimedAction.new ISBaseTimedAction.new = function(self, character, ...) --... is for extra arguments you don't care about --do stuff before local success, result = pcall(original, self, character) --do stuff after
if success then return result else return error(result) end end
to support functions with varying return results you can do
local original = ISBaseTimedAction.new ISBaseTimedAction.new = function(self, character, ...) --do stuff before local result = {original(self, character)} --do stuff after
return unpack(result) end
alternative way to patch multiple functions the same way
local patch = function(originalFunction) return function(self,character) --do stuff before local o = originalFunction(self,character) --do stuff after
return o end end ISBaseTimedAction_1.new = patch(ISBaseTimedAction_1.new) ISBaseTimedAction_2.new = patch(ISBaseTimedAction_2.new)
(-)The bad ways: Overwrite with same file in your mod or completely replacing functions are generally not recommended.
Events
If the function you want to change is added to an event then you need to remove the old function reference and add the new reference
Events.SomeEvent.Remove(original) Events.SomeEvent.Add(ISBaseTimedAction.new)
make a luaClosure that removes itself from an Event (Not advised to do with events during loading) (*) when making a new local function, if you want to refer to it from inside the function you must declare it first
local function OnTick() Events.OnTick.Remove(OnTick) --do stuff end Events.OnTick.Add(OnTick)
local OnTick OnTick = function() Events.OnTick.Remove(OnTick) --do stuff end Events.OnTick.Add(OnTick)