Strings and Byte Positions
Lesson 5 of 48 in Coddy's Lua for Go Developers course.
Go strings are byte sequences with zero-based byte indexes and half-open slices. Lua strings are also byte sequences, but string.sub uses one-based inclusive endpoints. The ASCII prefix shown can be translated by adjusting those positions.
Neither byte-slicing operation automatically follows Unicode characters. Go range decodes runes and utf8 helpers provide other units; a Lua port must deliberately choose an encoding strategy when the input is not restricted to ASCII.
Go
package main
import ("fmt")
func main(){
word:="map"; fmt.Println(word[:2])
}
Lua
local s = "map"
print(#s .. ":" .. s:sub(-2))Porting trap
Translate byte bounds carefully and do not promise character-safe slicing for arbitrary UTF-8.
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 Go Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte PositionsRecap: Format a Receipt4Functions and Closures
Functions and ArgumentsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Table FieldsTruth and Default ValuesBranches and BoundsValues and Table IdentityRecap: Admission RulesPractice on your own: Online Lua compiler