Strings and Byte Positions
Lesson 5 of 48 in Coddy's Lua for C Developers course.
A C string is typically a character array terminated by a zero byte. strlen counts bytes before that terminator, and array indexes begin at zero. Lua strings carry their own lengths, are immutable, and can contain embedded zero bytes. The length operator # reports the byte length without searching for a terminator.
For an ASCII string, string.sub selects bytes using one-based inclusive positions. Its method spelling s:sub(i, j) supplies the string automatically. Negative positions count backward from the end. The examples report the length and last two bytes of a three-byte word, using pointer arithmetic in C and a substring in Lua.
C
#include <stdio.h>
#include <string.h>
int main(void)
{
const char s[] = "map";
printf("%zu:%s\n", strlen(s), s + 1);
return 0;
}Lua
local s = "map"
print(#s .. ":" .. s:sub(-2))Porting trap
A C character offset and a Lua substring position differ by one. Byte slicing can also split a UTF-8 character; these exercises deliberately use ASCII.
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 C 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