1

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.

Vinicius Jarina
  • 797
  • 5
  • 16
Anoop Alex
  • 179
  • 1
  • 9
  • An example of constructing Lua table from C# Dictionary: http://stackoverflow.com/a/3050730/1150918 And building a Lua table using C API is pretty trivial. A fresh example of doing that: http://stackoverflow.com/a/20148091/1150918 – Kamiccolo Nov 22 '13 at 15:58
  • @Kamiccolo, copying the dictionary is not the same as iterating the original – finnw Nov 22 '13 at 16:04

1 Answers1

1

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

Vinicius Jarina
  • 797
  • 5
  • 16
  • when I try to run this code in Lua I get exception: attempt to call GetEnumerator (a nil value). I'm not sure why? I am loading assembly System.Collections.Generic – Anoop Alex Nov 22 '13 at 16:57
  • This doesn't work when my Dictionary type is however. x returns the value [one,PointClick.Pause+testClass]. How do I access the testClass properties and methods? – Anoop Alex Nov 22 '13 at 17:15
  • Also, what type is x returning? If I go back to the Dictionary it outputs [one,1] but this is not a table because x[1] returns 1 and x[1][1] returns error attempt to index ? (a number value)... – Anoop Alex Nov 22 '13 at 19:23
  • x will be the type of your Dictionary value, to access methods and properties you need to use : or . just like when you use a regular .NET object. – Vinicius Jarina Nov 24 '13 at 21:05