1
votes

I have a question regarding accessing userdata types in LuaInterface. When I pass my C# Dictionary to Lua and try to iterate through it using ipairs I get an error since ipairs is expecting a table and not a userdata object.

I suppose one solution is to convert the Dictionary type to a LuaTable type before passing it on to Lua but one use I want to put the userdata type to, is to bring in a Dictionary object into Lua and update the fields of the customType objects and call their methods in Lua. I don't know if this is possible but I'm pretty sure if I convert that Dictionary into a LuaTable of strings and ints, I will lose any chance to interface directly with customType from Lua.

I have looked online for info on working with userdata in Lua but the few examples I found interface with Lua through C/C++ and a stack which I dont really understand. Also, the sizeof method is used in some cases, which doesnt have an easy alternative in c#. Can someone please give me some pointers? The PIL section on User-Defined Types in C was not much help either.

1
An example of constructing Lua table from C# Dictionary: stackoverflow.com/a/3050730/1150918 And building a Lua table using C API is pretty trivial. A fresh example of doing that: stackoverflow.com/a/20148091/1150918Kamiccolo
@Kamiccolo, copying the dictionary is not the same as iterating the originalfinnw

1 Answers

1
votes

To iterate through collections elements using LuaInterface/NLua you need to use luanet.each instead ipairs. You don't need to create a LuaTable from your Dictionary.

luanet.each will use GetEnumerator,MoveNextand Current to iterate through Dictionary.

function luanet.each(o)
   local e = o:GetEnumerator()
   return function()
      if e:MoveNext() then
        return e.Current
     end
   end
end

Instead for x in ipairs(dict) use for x in luanet.each (dict)

Reference: https://github.com/NLua/NLua/blob/079b7966245cccb42c563abeb19290459e10934e/Core/NLua/Lua.cs#L245