Range Over Built in Lua
Based on your input, here’s the translation of the provided code to Lua in Markdown format suitable for Hugo.
range
iterates over elements in a variety of built-in data structures. Let’s see how to use range
with some of the data structures we’ve already learned.
Here we use range
to sum the numbers in a table (array-like structure in Lua).
nums = {2, 3, 4}
sum = 0
for _, num in ipairs(nums) do
sum = sum + num
end
print("sum:", sum)
range
on tables provides both the index and value for each entry. Above we didn’t need the index, so we ignored it with the blank identifier _
. Sometimes we actually want the indexes though.
for i, num in ipairs(nums) do
if num == 3 then
print("index:", i)
end
end
range
on tables can also iterate over key/value pairs. Here is how we can do it with Lua tables that act as maps.
kvs = {a = "apple", b = "banana"}
for k, v in pairs(kvs) do
print(k, "->", v)
end
range
can also iterate over just the keys of a table.
for k in pairs(kvs) do
print("key:", k)
end
range
on strings iterates over Unicode code points. The first value is the starting byte index of the rune
and the second the rune
itself.
for i = 1, #("go") do
local c = ("go"):sub(i, i)
print(i - 1, string.byte(c))
end
To run the Lua code, save it to a file (e.g., range.lua
) and then execute it using the Lua interpreter.
$ lua range.lua
sum: 9
index: 2
a -> apple
b -> banana
key: a
key: b
0 103
1 111
Next example: Pointers.