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.