type 'table' is not supported as a key by JSON.

I keep getting this error when I try to do what I thought I had already done in the StarExplorer tutorial.

My code is quite long, but here’s the (I think) important part:

local function loadScores() local file = io.open( filePath, 'r' ) if file then local contents = file:read( '\*a' ) io.close( file ) highScores = json.decode( contents ) end if not highScores or #highScores ~= #difficulties then print(highScores) highScores = {0, 0, 0} end end local function saveScores() local file = io.open( filePath, 'w' ) if file then print(unpack(highScores)) file:write( json.encode( highScores ) ) io.close( file ) end end

It’s the file:write line that’s throwing the error, of course.

For comparison, here’s the code from the tutorial:

local function loadScores() local file = io.open( filePath, "r" ) if file then local contents = file:read( "\*a" ) io.close( file ) scoresTable = json.decode( contents ) end if ( scoresTable == nil or #scoresTable == 0 ) then scoresTable = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } end end local function saveScores() for i = #scoresTable, 11, -1 do table.remove( scoresTable, i ) end local file = io.open( filePath, "w" ) if file then file:write( json.encode( scoresTable ) ) io.close( file ) end end

It certainly looks like JSON is encoding the table just fine. Can anyone speculate as to what might be going on?

Okay, I should’ve figured this out sooner! The keyword was “key.” I was accidentally storing data in the high scores table using another table as a key. So something like

print(json.encode{[{}] = 5})

is gonna cause errors.

Okay, I should’ve figured this out sooner! The keyword was “key.” I was accidentally storing data in the high scores table using another table as a key. So something like

print(json.encode{[{}] = 5})

is gonna cause errors.