I am currently trying to make a centralized, global prompt purchase function where effects such as a loading screen could play in the background of your purchase. However, I’ve ran into an issue. MarketplaceService has many Prompt Purchase methods, which are all specified for different types of purchases. Is there any way to automatically tell the purchase type of a product? Where you could do something like this:
I’ve heard loadstrings are dangerous, but I also realised you can’t use outside variables inside. So the parameters given to my function cannot be carried into the loadstring to automate purchases.
Global variables can be accessed (those declared without the local keyword)
Also, whatever you’re trying to do DOES NOT EVEN NEED LOADSTRINGS. Something people always forget is that the colon operator is a shortcut for dot operator, and dot operator can be done with any value using brackets to index for a value.
_G.PromptPurchase = function(player, id, purchaseType: string)
MarketplaceService[`Prompt{purchaseType}Purchase`](MarketplaceService, player)
end
I’m using string interpolation which was introduced to Luau earlier this year, so the syntax highlighting on the forum post looks off.
`hello {var} world`
--is the same as but performs worse than
'hello '..var..' world'
Also,
Since you’re using _G, it’s fruitless to annotate the formal parameter purchaseType: string because it will never be considered by virtue of you using _G. Do not use _G if you want the annotation to take any effect outside of the function block.
Also also, you should be using string literal because there are specific kinds of purchase types.
But, a little warning, using getfenv or setfenv in Luau is a TERRIBLE idea because it disables a lot of internal optimizations. Generally you don’t even want to use loadstrings. Stop talking about it!!!
setfenv is really only used to completely override the loaded function’s environment to “sandbox” it. Otherwise, you can just use getfenv and change values there.
setfenv() takes the function who’s environment you want to change, and then a table which is the environment. When I say override the environment, I really mean it:
This errored because I deleted the function’s environment, meaning that it doesn’t even have access to builtin functions such as print.
By the way, I didn’t mention this earlier but the “table” you get and use for environment manipulation are binding. The same table you used to set the environment can later be used to remotely manipulate the environment once more at a different time.
In this example, I created the env table first, set it to the function’s environment, and then through dark magic changed the builtin print to the builtin warn. So now calling print() inside the loaded function will actually call warn() instead.