How can I use a function parameter as function to be called from ModuleScript?

I’m trying to use a function parameter as the function to be called from a ModuleScript. Here is my code:

local canvas = workspace.ScratchCanvas
local motion = script.Motion
local Scratch = {}

function Scratch.motion(block)
	require(motion).block -- ?
end

return Scratch

Basically, the user defines the block and the parameters the block shall use. That is defined in another script called “code” which I want to look like this:

local Scratch = require(script.Parent.Scratch)
Scratch.motion--(insert block + parameters here)

I don’t know how to do that, tho :frowning:
I tried concatenating the parameter with the rest of the require() function, but that didn’t work. (I’m a beginner so excuse me if you found this funny)

Does someone know how to do this?

I believe you are talking about using bracket indexing [block] to access the function and variadic token to pass in the extra parameters.

local canvas = workspace.ScratchCanvas
local motion = script.Motion
local Scratch = {}

function Scratch.motion(block : string, ...)
--try printing
print(block, ...)
	require(motion)[block](...)-- ?
end

return Scratch

Then in the script

local Scratch = require(script.Parent.Scratch)
Scratch.motion("SomeFunctionName", 1,2,3, "Color Red")--(insert block + parameters here)

https://www.lua.org/pil/2.5.html

To represent records, you use the field name as an index. Lua supports this representation by providing a.name as syntactic sugar for a[“name”]. So, we could write the last lines of the previous example in a cleanlier manner as

a.x = 10                    -- same as a["x"] = 10
print(a.x)                  -- same as print(a["x"])
print(a.y)                  -- same as print(a["y"])

Thank you for the solution! Didn’t know that existed - I’ll keep that in mind.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.