Get all the arguments that were passed to Lua function

  Kiến thức lập trình

Let’s say I have this example code of a simple events generator below:

local eventsGenerator = {
    events = {},
    registerEvent = function(self, event)
        self.events[event] = {}
    end,
    subscribe = function(self, subscriber, event)
        table.insert(self.events[event], subscriber)
    end,
    fireEvent = function(self, event)
        for _, sub in pairs(self.events[event]) do
            local mySecretPayload = "secret"
            sub:callback(mySecretPayload)
        end
    end
}

eventsGenerator:registerEvent("SAY_HELLO")

eventsGenerator:subscribe(
    {
        name = "Peter", 
        callback = function(self, arg1, arg2)
            print("My name is " .. self.name)
            print(arg1)
            print(arg2)
        end
    },
    "SAY_HELLO"
)

eventsGenerator:subscribe(
    {
        name = "Harry", 
        callback = function(self)
            print("My name is " .. self.name)
        end
    },
    "SAY_HELLO"
)

eventsGenerator:fireEvent("SAY_HELLO")

Now, let’s say that my generator passes some arbitrary amount of arguments into the callback and as a subscriber I can’t see the source code.
Subscriber 1 tried to catch them with arg1, arg2. Of course there may be a lot more arguments and it’s hard to guess just with this method. But what is the best method to do this?

And also we are in Lua before 5.0, so … spread is not available.

I tried to look up such methods in Lua’s official docs, but couldn’t find.

LEAVE A COMMENT