How do I call a function method from a string

local DSS = game:GetService("DataStoreService")
local DataStore = DSS:GetDataStore("Server_DataStore")

local Method = "RemoveAsync"

local success, error = pcall(function()
    DataStore[Method]("89587322_Creation_1")
end)

if not success then
    warn(error)
    return
end

print("Remove Successful")

I get this error

Expected ':' not '.' calling member function RemoveAsync

and when I put a colon before the [Method] I get this error

Expected identifier when parsing method name, got '['

I’m doing this to simplify calling different methods such as SetAsync, RemoveAsync, GetAsync etc without having to make a new function. Is it possible?

Send DataStore as the first argument

DataStore[Method](DataStore, "89587322_Creation_1")

The Colon does this behavior automatically

2 Likes

This is not the issue but: you should not use “error” as an response value since error() is an roblox function and you are overriding it. This can lead to errors.

here is a different way to write @HugeCoolboy2007 response

local success, response = pcall(DataStore[Method], DataStore, "89587322_Creation_1")
print(success, response)
1 Like