Final: Inventory Port
Lesson 47 of 48 in Coddy's GDScript for Lua Developers course.
Challenge
EasyPort the Lua reference: input words, return alphabetically sorted word=count pairs joined by commas, or none. Words are lowercase ASCII, duplicates count separately. Do not change caller input.
Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.
Your code goes in exercise.gd. The supplied main.gd cannot be edited. Keep each class_name type in its named file.
Port this complete Lua reference to the specified GDScript API. The Lua driver reads a count, then one word per line. The target driver instead reads the specified JSON array. Both produce the same report. Words are lowercase ASCII; the sequence is dense and must remain unchanged.
Lua reference file inventory.lua:
local Inventory = {}
function Inventory.report(words)
local counts = {}
for _, word in ipairs(words) do
counts[word] = (counts[word] or 0) + 1
end
local keys = {}
for word in pairs(counts) do table.insert(keys, word) end
table.sort(keys)
local out = {}
for _, word in ipairs(keys) do
table.insert(out, word .. "=" .. counts[word])
end
if #out == 0 then return "none" end
return table.concat(out, ",")
end
return Inventory
Lua reference file main.lua:
local Inventory = require("inventory")
local count = assert(tonumber(io.read("*l")))
local words = {}
for i = 1, count do words[i] = assert(io.read("*l")) end
print("result=" .. Inventory.report(words))
Try it yourself
extends Node
func contract_ok(data: Array) -> bool:
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
All lessons in GDScript for Lua Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command CountPractice on your own: Online GDScript compiler