11-17-2011, 03:11 AM | #1 |
Stuff Do-er
Lua Team
Wiki Team Fortress Forever Staff |
Altering functions without overwriting them
Usually, when you create a Lua script and you need to alter a function that is defined in an include (the startup() function, for example) you'd have to copy it from the included file and then alter it, so as not to lose any functionality that the include had. This becomes especially bothersome when you need to alter things like baseflag:touch. It also creates a problem if the dev team updates that function in a base Lua, as your map will still have the old code overwriting any changes we made.
There is an alternative to overwriting, though. You can save the old function first, and then call the saved function from inside your new function. For example: Code:
-- save the old function in a variable startup_base = startup -- overwrite the function function startup() -- check to make sure the saved function is actually a function if type(startup_base) == "function" then -- call the saved function startup_base() end -- do whatever it is that you wanted to do end This next bit of code shows how to use a table to save the functions and how to save/call nested functions Code:
-- File: /includes/base_test.lua -- save all the functions in a table with the same name as the Lua file -- so we don't accidentally overwrite any saved functions in other files local base_test = {} -------------------------------------------------------------- -- Example: Saving a global function -------------------------------------------------------------- -- save the function in the table base_test.startup = startup function startup() -- check to make sure the saved function is actually a function if type(base_test.startup) == "function" then -- call the saved function base_test.startup() end -- do something end -------------------------------------------------------------- -- Example: Saving a nested function -------------------------------------------------------------- -- save the function in the table base_test.genericbackpack = {} -- need to make this a table before adding a key to it, otherwise Lua fails silently for some reason base_test.genericbackpack.touch = genericbackpack.touch function genericbackpack:touch( touch_entity ) if type(base_test.genericbackpack.touch) == "function" then -- call the saved function base_test.genericbackpack.touch( self, touch_entity ) end -- do something end
__________________
#FF.Pickup ยค Fortress-Forever pickups My Non-official Maps Released FF_DM_Squeek - FF_2Mesa3_Classic - FF_Siege_Classic Beta FF_Myth - FF_Redlight_Greenlight Sick of the people on the internet, always moanin'. They just moan. - Karl Pilkington Last edited by squeek.; 02-18-2013 at 02:17 AM. |
2 members found this post helpful. |
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
|
|