private static void Write(LuaTable table, IndentedTextWriter indentedTextWriter) { // Write empty tables in a single line if (table.Count == 0) { indentedTextWriter.Write("{}"); return; } // Determine whether to use auto-indexing for numeric keys. // Use auto-indexing if all n keys of numeric type form the sequence 1, 2, 3 .. n bool useAutoIndexing = table .Where(pair => pair.Key is double) .Select((pair, index) => new { Key = (double)pair.Key, Index = index }) .All(element => element.Key == element.Index + 1); // Serialize table indentedTextWriter.WriteLine("{"); using (indentedTextWriter.IndentBlock()) { var pairs = table.ToList(); for (int i = 0; i < pairs.Count; i++) { dynamic key = pairs[i].Key; dynamic value = pairs[i].Value; if (value is LuaComment) { // Comment. This is easy. Write(value, indentedTextWriter); } else { // Actual entry, not a comment if (useAutoIndexing && key is double) { // Use auto-indexing: omit the key Write(value, indentedTextWriter); } else { // Use key-value syntax if (key is string && IsValidIdentifier(key)) { // Use identifier syntax for key indentedTextWriter.Write(key); } else { // Use bracket syntax for key indentedTextWriter.Write("["); Write(key, indentedTextWriter); indentedTextWriter.Write("]"); } indentedTextWriter.Write(" = "); Write(value, indentedTextWriter); } // Figure out whether to add a comma if (pairs.Skip(i + 1).Any(pair => !(pair.Value is LuaComment))) { indentedTextWriter.WriteLine(","); } else { indentedTextWriter.WriteLine(); } } } } indentedTextWriter.Write("}"); }