1local NL = "\n" -- New line character
2local HW = 70 -- Header width
3
4local function header(title)
5 print(NL .. string.rep("*", HW))
6 print(string.format(" > %s", title))
7 print(string.rep("*", HW) .. NL)
8end
9
10-- Loops and tables.
11
12header("Loops and tables")
13
14for i=1, 5 do
15 print("- Loop with index " .. i)
16end
17
18local names = {
19 "John",
20 "Bob",
21 "Grug",
22}
23
24for _, name in pairs(names) do
25 print(string.format("* This create is called %s.", name))
26end
27
28-- Math stuff.
29
30header("Math stuff")
31
32print("Square root of 16:", math.sqrt(16))
33print("Absolute value of -7:", math.abs(-7))
34print("Ceiling of 2.3:", math.ceil(2.3))
35print("Floor of 2.9:", math.floor(2.9))
36print("Rounding 3.6:", math.floor(3.6 + 0.5))
37
38print("Cosine of 0:", math.cos(0))
39print("Sine of 90 degrees:", math.sin(math.rad(90)))
40
41math.randomseed(os.time())
42print("Random number (1-100):", math.random(1, 100))
43
44print("2 to the power of 3:", math.pow(2, 3))
45print("Natural log of 2.71828:", math.log(2.71828))
46print("Base-10 log of 1000:", math.log10(1000))
47
48print("Pi:", math.pi)
49print("Convert 180 degrees to radians:", math.rad(180))
50print("Convert Pi radians to degrees:", math.deg(math.pi))
51
52-- Coroutines.
53
54header("Coroutines")
55
56function producer()
57 return coroutine.create(function()
58 for i = 1, 3 do
59 print("Producing:", i)
60 coroutine.yield(i)
61 end
62 end)
63end
64
65function consumer(prod)
66 while true do
67 local status, value = coroutine.resume(prod)
68 if not status or value == nil then break end
69 print("Consumed:", value)
70 end
71end
72
73co = producer()
74consumer(co)
75
76function sneaky()
77 print("Coroutine starts")
78 coroutine.yield() -- Pause and give control back.
79 print("Coroutine resumes after yield")
80end
81
82co = coroutine.create(sneaky)
83
84print("First resume:")
85coroutine.resume(co)
86
87print("Second resume:")
88coroutine.resume(co)
89
90-- IO stuff.
91
92header("File IO")
93
94print("Reading file adams.txt...\n")
95
96local file = io.open("adams.txt", "r")
97if not file then
98 print("Failed to open file.")
99 return
100end
101
102for line in file:lines() do
103 print(line)
104end
105
106file:close()
107
108-- Exposing C functions.
109
110header("Exposing C functions")
111
112local result = c_sum(3, 5)
113print("Sum is", result)