How to call a function as a method if by using a variable instead of the function name?

The reason why I am trying to call commandName as a method is to pass the “self” argument to the “tp” function, so the tp function can then use self.teleport(args). The root problem is that I can’t do this:

https://gyazo.com/d03f9e6af3c4de1f16a46ef03513d3f8
(line 18)

local commands = {
teleport = function(args)
end,
tp = teleport – the script doesn’t recognize “teleport” as a defined function yet
}

so, what I am trying to do is call the function as a method:
commands:commandName(args)

which would allow the “teleport” function to refer to the “tp” function in the same table by doing teleport = self.tp

You need to use [] brackets to index table values, like this:

commands[CommandName](args)

Btw you might want to unpack the args

2 Likes

The reason why I am trying to call commandName as a method is to pass the “self” argument to the “tp” function, so the tp function can then use self.teleport(args). The root problem is that I can’t do this:

https://gyazo.com/d03f9e6af3c4de1f16a46ef03513d3f8
(line 18)

local commands = {
teleport = function(args)
end,
tp = teleport – the script doesn’t recognize “teleport” as a defined function yet
}

Hiya please try to use your existing topic rather than making a new one (duplicating).

https://devforum.roblox.com/t/how-to-call-a-function-as-a-method-if-by-using-a-variable-instead-of-the-function-name/310366/2

I deleted that one because it didn’t follow the guidelines for the Code Review section, and posted it here instead

In future just message a dev relation member and ask for the topic to be moved :blush:

1 Like

local commands = {
teleport = function(args)
– teleport code
end,
tp = function(args),
local commands = GetCommandsTable()
commands.teleport(args)
end
}

function GetCommandsTable()
return commands
end

Or implement aliases

local cmds = {}
local function AddCommand(name, func, alias)
    cmds[name] = func
    for i,v in pairs(alias) do
        cmds[v] = func
    end
end

AddCommand("teleport", function(args)
    if args[2] then
        args[1].Character:SetPrimaryPartCFrame(args[2].Character.PrimaryPart.CFrame)
    end
end, {"tp"})

--chatted or whatever:
local cmd = cmds[name]
if cmd then
    cmd(args)
end
1 Like