Passing C# collection to back to Lua

梦想的初衷 提交于 2019-12-10 11:52:26

问题


I have a DLL written in C# that is used by Lua scripts. The scripts "require CLRPackage". So far I can load_assembly() and import_type() to get at the classes and methods in my DLL. I'm passing back simple values and strings, and that all works.

No I need to pass a generic collection back to Lua. I believe that what Lua will see is a table, but it isn't clear to me how to create that table in C# and pass it back.

This seems to be a similar question, but I'm not seeing how to implement it. Is there another solution or one with a stripped down code fragment?


回答1:


Now I need to pass a generic collection back to Lua. I believe that what Lua will see is a table

It won't. Lua will see a CLR object (rather, a userdata proxy for the CLR object).

If you had a method in your C# class like this:

public List<string> GetList()
{
    return new List<string> { "This", "bar", "is", "a" };
}

The Lua side (after you loaded the module, grabbed the class and instantiated it as, say, foo):

local list = foo:GetList()
print(list)

That will give you something like System.Collections.Generic.List1[System.String]: 33476626. This is a userdata, not a table, so you can't use next or pairs to iterate through it, you have to interact with it as it were a C# List<string>:

local it = list:GetEnumerator()
while it:MoveNext() do
  print(it.Current)
end

This is very ugly, non-idiomatic Lua to be sure (even non-idiomatic C#, given that you'd use foreach in C#), but I don't think there's any automatic marshalling between LuaInterface types and CLR types. Kinda hard to tell; LuaInterface documentation is almost nonexistent.

You could write your own routines to marshal between Lua and CLR types, like:

function listToTable(clrlist)
    local t = {}
    local it = clrlist:GetEnumerator()
    while it:MoveNext() do
      t[#t+1] = it.Current
    end
    return t
end
    
...
    
local list = listToTable(foo:GetList())
for key, val in pairs(list) do
  print(key,val)
end

Add a dictToTable and you'd be pretty much covered.



来源:https://stackoverflow.com/questions/10941563/passing-c-sharp-collection-to-back-to-lua

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