1

I don't get the point why this is happening. I am using Moonsharp to run LUA scripts in my application an I created a LUA function IN(v, ...) and I'd like to itterate over the ... parameter with pairs.

IN('param1', 'param2', 'param1') -- expected it to return true
function IN(v, ...)
    local args = ...
    local res = true
    for i, v in pairs(args) do
        if valueIn == v then
            res = true
            break
        end
    end
    return res
end

If it gets called I recieve the folowing exception:

"MoonSharp.Interpreter.ScriptRuntimeException" bad argument #1 to 'next' (table expected, got string)

So I decided to check if there is a string instead of a Table in my ... variable.

function args(v, ...)
    return ...
end

The return value in C# is a Tuple of 2 values with 'param2' and 'param1', so it should work with pairs or ipairs, shouldn't it?

Thanks in advance.

greg-e
  • 374
  • 4
  • 18

1 Answers1

5

Using this definition like in your example:

function test(...)
  local arg = ...
end

and calling

test(1,2,3)

will result in

local arg = 1, 2, 3

which of course only assigns 1 to arg. The rest is omitted.

But as the table constructor takes ... as input you may write

local arg = {...} or and then happily iterate over your new table arg. ... is not a table as lua just told you. Hence you cannot iterate over ...

Alternatively local arg = table.pack(...) will also work.

The vararg system has been changed in Lua 5.1, in case you're curious https://www.lua.org/manual/5.1/manual.html#7.1

The vararg system changed from the pseudo-argument arg with a table with the extra arguments to the vararg expression. (See compile-time option LUA_COMPAT_VARARG in luaconf.h.)

Befor you could do something like

function test(...)

  for k,v in pairs(arg) do
    print("I'm a generic for loop yeah!!!")
  end

end

So the local arg = {...} was not necessary.

Piglet
  • 27,501
  • 3
  • 20
  • 43
  • Just for fully understanding the point. What kind of object is ... by itself, if it is no table? – greg-e Jul 21 '17 at 12:12
  • 1
    @georgpoweleit its an expression that evaluates to a list of values. similar to a function call that returns multiple values. maybe this is worth a read: http://lua-users.org/wiki/VarargTheSecondClassCitizen – Piglet Jul 21 '17 at 13:12