Hello, Community. I have a question that concerns something I tried to do in Roblox Lua and ran into an error.
Question: How could I go about calling a method by it's string name?
For example:
-- In a Local Script. local mname = "GetService" if game[mname]("Workspace") ~= nil then print("Workspace isn't nil.") end
This outputs an error saying: "Expected ':' not '.' calling member function GetService."
I've tried a lot of other things I could think of to achieve this, but no success so far.
I know that it should be something like:
if game:GetService("Workspace") ~= nil then print("Workspace isn't nil.") end
But how could I call the GetService method with it's string name? Thanks in advance.
Basically just a writeup of what incapaxian said
The :
operator is just "syntax sugar" for "." but with the first argument being the object you're calling from. "Syntax sugar" is a term for something which is syntactically equivalent to something else, but that is easier and cleaner to use. If you ever use Haskell, get ready for a lot of syntax sugar, because the language is basically built on it.
For example, these are equivalent:
game:GetService("Players") game.GetService(game, "Players")
Furthermore, in Lua, the .
operator is just sugar for an array access. The following are equivalent
table["banana"] table.banana
Every different data structure in Lua is just a table wearing a different hat, so these rules apply to basically any data structure, including objects.
Therefore, this should do what you want:
function methodCall(owner, methodName, arguments) owner[methodName](owner, unpack(arguments)) end methodCall(game, "GetService", {"Players"})