Lua - Iterate Through Table With nil Values

Posted by Tony Trozzo on Stack Overflow See other posts from Stack Overflow or by Tony Trozzo
Published on 2010-03-25T03:50:50Z Indexed on 2010/03/25 3:53 UTC
Read the original article Hit count: 545

Filed under:
|
|

My lua function receives a table that is of the array form:

{
    field1,
    field2,
    nil,
    field3,
}

No keys, only values. I'm trying to convert this to a pseudo CSV form by grabbing all the fields and concatenating them into a string.

Here is my function:

function ArenaRewind:ConvertToCSV(tableName)
    csvRecord = "\n"

    for i,v in pairs(tableName) do
        if v == nil then v = "nil" end
        csvRecord = csvRecord .. "\"" .. v .. "\""
        if i ~= #tableName then
            csvRecord = csvRecord .. ","
        end
    end

    return csvRecord
end

Not the prettiest code by any means, but it seems to iterate through them and grab all the non-nil values. The other table iteration function is ipairs() which stops as soon as it hits a nil value.

Is there any easy way to grab all of these fields including the nil values? The tables are various sizes, so I hope to refrain from accessing each part like an array [i.e., tableName[1] through tableName[4]) and just grabbing the nil values that way.

Thanks in advance.

© Stack Overflow or respective owner

Related posts about lua

Related posts about tables