Moonsharp pairs(…) raises exception “bad argument #1 to 'next' (table expected, got string)”

半城伤御伤魂 提交于 2019-12-11 07:39:30

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/45218769/moonsharp-pairs-raises-exception-bad-argument-1-to-next-table-expected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!