使用 MoonSharp 在 Lua 中循环遍历 C# 字典

我想要遍历这样的东西:

public readonly IDictionary<int, Entity> Entities = new Dictionary<int, Entity>();

在 Lua 中使用 MoonSharp。从文档中可以看出,MoonSharp 可以自动将 IDictionary 类型转换为表格?

然而,尝试像这样做...

for k,v in pairs(World.Entities) do
  -- something
end

会出现以下错误:

ScriptRuntimeException: bad argument #1 to 'next' (table expected, got userdata)

为什么 MoonSharp 没有将我的字典转换成表格?有什么我忽略的东西吗?

谢谢!

点赞
用户9184580
用户9184580

我仍然不知道为什么 MoonSharp 没有自动处理这个问题 - 起初我以为可能是我的 'Entity' 类型有问题,但是我已经将其替换并测试过,还是一无所获。

我现在的解决方法是在我的 .lua 文件内部处理转换。

function convert.dictTable(clr)
  local table = {}
  local enumerator = clr:GetEnumerator()

  while enumerator:MoveNext() do
    table[enumerator.Current.Key] = enumerator.Current.Value
  end

  return table
end
2018-01-10 05:30:18