Help with lua function error

Hello i am learning functions and i get an error, what’s wrong and how could i print this?

local function namedArguments(args)
	return args.name .. "'s birthday: " .. args.dob
end
namedArguments{name="Bob", dob="4/1/2000"}

print(namedArguments)
local function namedArguments(args)
	local str = args.name .. "'s birthday: " .. args.dob
    return str
end

local str = namedArguments{name="Bob", dob="4/1/2000"} -- set what's returned to a variable, you were printing the function

print(str)
4 Likes

wow thanks you a lot!! :smiley:

and do you know how to fix it? :frowning:

local function variableArguments(...)

    print(...)

end

There doesn’t seem to be anything wrong with that code, are you passing correct arguments?

@HugeCoolboy2007 's code works.
You do not need to wrap single parameters such as strings and tables within ().

function f(a)

end

f{}
f""

i don’t know (i am not sure) how to do variableArguments in a function :frowning:

local function variableArguments(...)

    print(...)

end
local function variableArguments(...)
    print(...)
end

variableArguments(1, 2, 3, 4, 5, "string") -- pass any length of arguments through it

If you want to put them all in a table, you would do:

local function variableArguments(...)
    local arguments = table.pack(...) or {...} -- this places all the arguments into a table as an array
    print(...)
end
1 Like

To define variable elements you use the ... syntax.

If you know you what the first few parameters passed to a variable function is then you can give them definitions.

local function variableArguments(hello, world, a, ...)
--// hello is a reference to "hi"
--// world is a reference to "soup"
--// a is a reference to 1
end

variableArguments("hi", "soup", 1, {}, 123)

If you want to select an nth variable argument that has not been associated with a variable then you can use the select keyword or wrap the tuple inside a table.

local function variableArguments(hello, world, a, ...)
    local second = ({...})[2]
    local _second = select(2, ...)
--// both second and _second reference the empty table, {}, which is the second undefined variable
end

variableArguments("hi", "soup", 1, {}, 123)
2 Likes

The 3 ... mean that with that I can add more arguments? And why do you make variableArguments (" hi "," soup ", 1, {}, 123) out of the function?

variableArguments("hi", "soup", 1, {}, 123) preforms a function call of variableArguments with parameters "hi", "soup", 1, {}, and 123.

the ... gives reference to any parameters that you did not explicitly define in the function’s parameters.
See the link posted on Variadic functions

1 Like

Thank you so much guys!! really! thanks for the explanation of everything :smiley: