Create a variable to a function with pre-defined arguments

Hello!

So, straight to the point. Say I’ve got a function

local function PrintNum(num: number)
    print(num)
end

We all know that we can assign another variable to that function like so

local func: (number) -> () = PrintNum
func(7) -- Same output as 'PrintNum(7)'

But my question is, could I pre-define the arguments inside the function? This might sound a bit confusing, so let me try to give you an example.

-- This will obviously just call the 'PrintNum' function with the argument '7' and set
-- predefinedPrintNum to nil, but could it be done so that it wouldn't?
local predefinedPrintNum: (number) -> () = PrintNum(7)

predefinedPrintNum() -- I want this to call 'PrintNum' with the argument '7', without me needing to input the argument

Now I know I could make something like this to do that

local function PrintNum(num: number): () -> ()
    return function()
        print(num)
    end
end

local predefinedPrintNum: () -> () = PrintNum(7)
predefinedPrintNum() -- Outputs '7'

But I’m wondering, is there a built-in way in luau to do this?

there isnt a built-in way to pre-define arguments for a function directly in the way ur describing. But ur approach of returning a function from PrintNum is a way to achieve it.

2 Likes

Alright, thanks!
(3O characters)

1 Like

This is actually functional programming, you’re returning a closure with knowledge of some enclosed state, for example, here’s an add function that takes the first number and returns a closure to add to the right hand side of it:

local function addClosure(n1: number)
  return function(n2: number)
    return n1 + n2
  end
end

This is very much the way to do this, and you see it sometimes in Roblox code

(i’m pretty sure this is called currying but dont quote me on that)

3 Likes

Like the others said, there’s no built-in way to do this. If you don’t want to use a separate function (e.g. optional parameters in your function), you can check if it’s nil. This would replicate the behaviour Python has:

def foo(param1, param2 = "placeholder")
    print(param1, param2)

foo(1) #--> 1 placeholder
foo(1, param2 = "overwritten") #--> 1 overwritten
local function foo(param1: number, param2: string?)
    --just check if it's nil
    if not param2 then
        param2 = "your predefined parameter" :: string
    end
    print(param1, param2)
end

foo(1) --> 1 your predefined parameter
foo(1, "overwritten") --> 1 overwritten
local function foo(param1, param2)
  param2 = param2 or "placeholder"
end

works for all datatypes except boolean, and for boolean type you can just

param2 = if param2 == nil then "placeholder" or param2

Picky much… just kidding
yeah both of those work i just did an if statement cuz y not :>

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