Home > Enterprise >  How do i redirect all class calls in LUA?
How do i redirect all class calls in LUA?

Time:03-01

Ok i'm kinda bad at this so i'll explain by giving a simple example first:

Say i have a "class", lets name it MyClass, lets say it has a function named MyFunction, we can access this by calling the function from any MyClass objects like MyClassObject:MyFunction().

If i didn't have access to that function, and wanted to add a new behaviour that executes beforehand, i can do something like:

MyClass.OriginalMyFunction = MyClass.MyFunction -- store old function

function MyClass:MyFunction(args)
    --Do something beforehand
    MyClass:OriginalMyFunction(args) --call original function with same args
end

This was just a simple example, but what i need is doing the same for all possible functions in a class. As in calling any functions on MyClassObject should execute some code before executing that function.

Is this possible? If so, how do i do it?

CodePudding user response:

it can be done via metatables

somewhat crude example:

local MyClass = {}
function MyClass:new()
  local newObj = {
    x = 0
  }
  self.__index = self
  return setmetatable(newObj, self)
end

function MyClass:get_x()
  print("hello from get_x")
  return self.x    
end

local HookedMyClass = {}

function HookedMyClass:new()
  local t = MyClass:new()
  local mt = {
      __index = function(table, key)
          print("hook")
          return(MyClass[key])
      end
  }
  return setmetatable(t, mt)
end

local hooked = HookedMyClass:new()

print(hooked:get_x())

CodePudding user response:

here is an inheritance example where some code is added to all your functions:

function new (parent)
    local child =  {} 
    for k,v in pairs(parent) do
       if type(v)=="function" then    
          child[k] = function(...) 
                      print("inherit:")
                      return v(...)
          end
       else child[k] = v
       end
    end
    return child
end

my_class = new(class)

class.bar("arg1","arg2")
my_class.bar("arg1","arg2")
print(class.a)
print(my_class.a)

result:

bar arg1 arg2
inherit:
bar arg1 arg2
value
value
  • Related