Search code examples
arraysindexingluagarrys-modsource-engine

Table[1] returning nil when table does exist and has values


local mapSpawnsData = {}
local JSONData = file.Read(filePath)            -- read file as json text
mapSpawnsData = util.JSONToTable(JSONData)      -- convert JSON to table

print("TABLE:")
PrintTable(mapSpawnsData)
print("TABLE[1]:")
print(tostring(mapSpawnsData[1]))

This is a script for a game called garrysmod. PrintTable() is a function I can call included in the game.

The code snippet I included returns this: (Same output if I remove the tosring())

TABLE:
gm_construct:
            1       =       -1303.524902 167.472397 -44.081600
            2       =       1250.890137 331.746185 -44.081600
            3       =       674.012085 223.775604 -32.148102
TABLE[1]:
nil

I expected to get back "gm_construct". What am I missing here?


Solution

  • What you didn't notice is that PrintTable printed gm_construct: first and then 1 = . That means the table actually contains only gm_construct key with a table with 3 keys.

    To be able to always read PrintTable output properly look at the ident. 1 = is tabulated to the right once, this means they are keys of something nested in the table you initially printed.

    If this still confuses you, try to run this:

    for k,v in pairs(mapSpawnsData) do
        print(k, "=", v)
    end
    

    This won't print nested content.

    To make your code work do mapSpawnsData.gm_construct[1] or mapSpawnsData["gm_construct"][1]