Menu
CoddyTech

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)
end

Porting trap

Use one-based Lua sequence positions and stop relying on ipairs across nil holes.

challenge icon

Challenge

Easy

Each 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))
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