Search code examples
c#luajson.netnlua

Iterating over JArray in NLua


I'm trying to iterate over a JArray in NLua, but can't somehow. JArray's are treaten as userdata (what is userdata?) and thus can't be iterated over.

Converting the JArray to an JValue[] with a c# method doesn't work either.

There are two possible solutions as far as I can see. 1. Getting a working Iterable function for nlua. 2. Converting the JArray to a Lua Table and then use a for loop on top of it.

I have not succeeded at any of those two. Is there anyone with more experience on this? Thank you in advance.

things I tried:

regCommands is a JArray containing a lot of JObjects in JTokens

    jArray = Json:parseJArray(regCommands)

    for k, v in ipairs(jArray) do

        print(k.. " ".. v)

    end

this gives the error on ipairs(jArray) that jArray is userdata.

    Json:parseJArray(JArray)

is a c# function wich takes a JArray and spits out a JToken[]

something else I tried:

    keyVal = regCommands.First
    while keyVal ~= nil do
        if (type(JProperty)) then
            regCommands[keyVal.Name:lower()] = keyVal.First
        end
        keyVal = keyVal.Next
    end

this crashes at regCommands[keyVal.Name:lower()] = keyVal.first whitout any logical reasons.

even getting a c# enumerator doesn't work

    enumCommands = regCommands:GetEnumerator()

    enumCommands:MoveNext()
    repeat

        enumCommands:MoveNext()
    until enumCommands:Current() ~= nil

Solution

  • To iterate over a .NET collection you can use luanet.each function, which will return the function to iterate through .NET enumerables objects.

    local each = luanet.each
    
    for k in each(jArray) do
        print (k)
    end
    

    Exemple: https://github.com/codefoco/NLuaBox/blob/00af36aa480281ae33835173430a806c54c2f9dc/Resources/source/ScriptsDataSource.lua#L166