Bytes and UTF-8 Libraries
Lesson 4 of 29 in Coddy's Lua for Luau Developers course.
Luau offers a built-in utf8 library. Lua 5.1 has no standard UTF-8 library, although a host may install one. Both languages still store strings as byte sequences: #s measures bytes, and string.sub slices inclusive byte positions starting at one. Port a Unicode-aware operation by supplying an appropriate library or explicitly narrowing the data contract. Do not silently substitute byte length for character counting. The exercise deliberately uses ASCII, where each character occupies one byte, so its last-two-character operation can use s:sub(-2). Existing pattern operations are also byte-oriented.
Luau
local s = "é"
print(`{#s}:{utf8.len(s)}`)Lua 5.1
local s = "é"
print(#s)Porting trap
The source example counts Unicode code points as well as bytes. The target example reports bytes only; these are different measurements, not conflicting runtime results.
Challenge
EasyInput is one ASCII line, possibly empty. Return its byte length, a colon, and its last two characters (or all characters if shorter).
Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Try it yourself
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for Luau Developers
1Syntax and Runtime
Run Lua ModulesInterpolation to TextFloor Division and NumbersBytes and UTF-8 LibrariesFalse Values and DefaultsConditional ExpressionsPractice on your own: Online Lua compiler