Strings and Byte Indexes
Lesson 5 of 48 in Coddy's Lua for GDScript Developers course.
GDScript strings expose methods such as length() and substr(start, length), with positions starting at zero. Lua's string library instead provides string.sub(text, first, last): positions start at one and the final position is inclusive. Negative positions count backward from the end, so string.sub(text, -2) takes the last two bytes. The Lua length operator #text counts bytes, whereas GDScript's length() counts Unicode code points. ASCII examples let those counts agree. Do not generalize that agreement to accented text or emoji. Use the library's byte-oriented rules when implementing a length-and-suffix operation whose input contract explicitly promises ASCII.
GDScript 4
extends SceneTree
func _init():
var label = "POTION"
print(str(label.length()) + ":" + label.substr(1, 2))
quit()Lua 5.1
local label = "POTION"
print(#label .. ":" .. string.sub(label, 2, 3))Porting trap
Lua's third substring argument is the final position, not a length. Porting text.substr(1, 2) requires string.sub(text, 2, 3) for ASCII text.
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 GDScript Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Missing ValuesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission RulesPractice on your own: Online Lua compiler