Array Loops to ipairs
Lesson 14 of 48 in Coddy's Lua for Go Developers course.
Go range over a slice yields zero-based indexes and values. Lua ipairs yields one-based integer keys and values until the first nil key. Keep the Lua sequence dense and adjust positions when they contribute to an output calculation.
A map range in Go and pairs in Lua do not provide the same contract as sequential slice traversal. Named table fields are outside an ipairs sequence. Do not use a hole as if later elements would automatically shift.
Go
package main
import ("fmt")
func main(){
labels:=[]string{"a","b"}; for i,v:=range labels {fmt.Printf("%d:%s\n",i,v)}
}
Lua
local labels = {"a", "b"}
for i, value in ipairs(labels) do
print(i .. ":" .. value)
endPorting trap
Use one-based Lua sequence positions and stop relying on ipairs across nil holes.
Challenge
EasyEach input line is one nonempty label. Return comma-separated index:label pairs using one-based indexes; return none for no lines.
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 Rules3Iteration and Flow
Numeric for and Limitswhile and repeatArray Loops to ipairsFiltering and Early ExitRecap: Reading Stats6Ordering, Modules and Errors
Sorting and ComparatorsParsing with Lua PatternsModules and requireStatus Codes to pcallRecap: Validate a BatchPractice on your own: Online Lua compiler