Menu
CoddyTech

Final: Inventory Port

Lesson 47 of 48 in Coddy's GDScript for Luau Developers course.

challenge icon

Challenge

Easy

Port the Luau 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. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.

Complete Luau reference program. input.luau holds the already parsed input array for this demonstration; change that fixture to try other cases. Run main.luau with the other files beside it. The GDScript task keeps its supplied JSON stdin driver. This source reference avoids depending on host-specific JSON or stdin APIs. Numbers here represent integers within the stated task bounds.

File inventory.luau:

local Inventory = {}
function Inventory.report(words: {string}): string
    local counts: {[string]: number} = {}
    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 parts = {}
    for _, word in ipairs(keys) do
        table.insert(parts, word .. "=" .. tostring(counts[word]))
    end
    return if #parts == 0 then "none" else table.concat(parts, ",")
end
return Inventory

File input.luau:

return {"b", "a", "b"}

File main.luau:

local Inventory = require("./inventory")
local words = require("./input")
print("result=" .. Inventory.report(words))

Reference output:

result=a=1,b=2

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 Luau Developers

Practice on your own: Online GDScript compiler