sgowd
sgowd

Reputation: 1034

argument name in the lua function call

I am looking for a more pleasant way to add an argument name while calling a function.

Something which is better than either of these

local ret =  foo( --[[argNam1 =]] true)
local ret =  foo( true ) -- first argument is argName1

I tried

local ret =  foo( argNam1 = true)

but I got error

')' expected near '='

Upvotes: 3

Views: 582

Answers (1)

geekhunger
geekhunger

Reputation: 550

You could use named parameters, if that's what you want. Lua tables are good for imitating that behavior. So instead of passing all parameters separated by a comma, you pass a single table object; that has named keys.

If that is your foo() function:

local foo(parameters)
    print(parameters.argNam1)
end

Then you could call it like: local ret = foo{argNam1 = true} Or call it like this:

local arguments = {
    argNam1 = true,
    argNam2 = "foobar"
}
local ret = foo(arguments)

Upvotes: 2

Related Questions