Debian Codegraph @

tests/data/notebooks/outputs/ipynb_to_myst/lua_example.md

raw
1 ---
2 kernelspec:
3 display_name: Lua
4 language: lua
5 name: lua
6 ---
7
8 Source: https://www.lua.org/pil/19.3.html
9
10 +++
11
12 # Sort
13
14 +++
15
16 Another useful function on arrays is table.sort, which we have seen before. It receives the array to be sorted, plus an optional order function. This order function receives two arguments and must return true if the first argument should come first in the sorted array. If this function is not provided, sort uses the default less-than operation (corresponding to the `<ยด operator).
17
18 +++
19
20 A common mistake is to try to order the indices of a table. In a table, the indices form a set, and have no order whatsoever. If you want to order them, you have to copy them to an array and then sort the array. Let us see an example. Suppose that you read a source file and build a table that gives, for each function name, the line where that function is defined; something like this:
21
22 ```{code-cell}
23 lines = {
24 luaH_set = 10,
25 luaH_get = 24,
26 luaH_present = 48,
27 }
28 ```
29
30 Now you want to print these function names in alphabetical order. If you traverse this table with pairs, the names appear in an arbitrary order. However, you cannot sort them directly, because these names are keys of the table. However, when you put these names into an array, then you can sort them. First, you must create an array with those names, then sort it, and finally print the result:
31
32 ```{code-cell}
33 a = {}
34 for n in pairs(lines) do table.insert(a, n) end
35 table.sort(a)
36 for i,n in ipairs(a) do print(n) end
37 ```
38
39 Note that, for Lua, arrays also have no order. But we know how to count, so we get ordered values as long as we access the array with ordered indices. That is why you should always traverse arrays with ipairs, rather than pairs. The first imposes the key order 1, 2, ..., whereas the latter uses the natural arbitrary order of the table.
40
41 +++
42
43 As a more advanced solution, we can write an iterator that traverses a table following the order of its keys. An optional parameter f allows the specification of an alternative order. It first sorts the keys into an array, and then iterates on the array. At each step, it returns the key and value from the original table:
44
45 ```{code-cell}
46 function pairsByKeys (t, f)
47 local a = {}
48 for n in pairs(t) do table.insert(a, n) end
49 table.sort(a, f)
50 local i = 0 -- iterator variable
51 local iter = function () -- iterator function
52 i = i + 1
53 if a[i] == nil then return nil
54 else return a[i], t[a[i]]
55 end
56 end
57 return iter
58 end
59 ```
60
61 With this function, it is easy to print those function names in alphabetical order. The loop
62
63 ```{code-cell}
64 for name, line in pairsByKeys(lines) do
65 print(name, line)
66 end
67 ```