简体   繁体   中英

Accessing userdata properties and methods in Lua

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.

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 , MoveNext and 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM