How can i make a function with arguments like this

Any idea on how i can make a function that reads a table argument such as this

This requires OOP (object oriented programming). You can read more about it here.

I already know all of OOP, i just wanna know how i can make for example a function like this New { } instead of New()

func{...} is syntactic sugar for func({...}). In your example New{"Apple"} is identical to New({"Apple"}).

You can just define a function then call the function using the table syntax.

When i do that it errors

image

function printArgs(t)
   -- define the function normally
   print(table.unpack(t))
end

-- if the function only takes 1 argument and the argument is a table, you can call it like this:
printArgs {
   "Hello World!",
   "This is a vararg",
   "Function called",
}

This gave me this err image

Here’s the main script

Here’s the module script

image

Wouldn’t you need to do

function NewInstance:Construct(t)?

No Construct is equal to self aka Construct.new() in OOP and Construct is a function

1 Like

Well I don’t know how to do it then, but I wrote something else as an alternative.

local construct = {}
construct.__index = construct

function construct.new()
  local self = {}
  setmetatable(self, construct)

  function self:construct(t)
    print(unpack(t))
  end

  return self
end


return construct

I wrote it in Lua, not Luau, so just change it for Luau’s syntax

Your script would need to look like:

-- from the Construct module script
local Construct = {}
Construct.__index = Construct

Construct.__call = function(self, t)
   -- 'self' is the variable that points back to the table it's attached to
   -- 't' would be the table that was sent
   -- for more info about 'self': https://devforum.roblox.com/t/what-is-self-and-how-can-i-use-it/368697/2

   -- the code to be executed when someone does "variable {...}" goes in here, for now, this is an example code snippet
   print(table.unpack(t))
end

function Construct.new()
    local NewInstance = setmetatable({}, Construct)

    return NewInstance
end
-- in another script
local Construct = require( --[[<< Path to the module >>]]-- )
local New = Construct.new()

local MyPart = New {
   "Hello World!" -- test argument
}
1 Like