Menu
CoddyTech

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 icon

Challenge

Easy

Input 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for Go Developers

Practice on your own: Online Lua compiler