ch06 exercises
This commit is contained in:
8
exercises/ch06/ex6_1.lua
Normal file
8
exercises/ch06/ex6_1.lua
Normal file
@@ -0,0 +1,8 @@
|
||||
local function print_array(a)
|
||||
for _, v in pairs(a) do
|
||||
print(v)
|
||||
end
|
||||
end
|
||||
|
||||
print_array({ 1, 2, 3 })
|
||||
print_array({ "a", 2, "hello", 99 })
|
||||
5
exercises/ch06/ex6_2.lua
Normal file
5
exercises/ch06/ex6_2.lua
Normal file
@@ -0,0 +1,5 @@
|
||||
local function f(...)
|
||||
return select(2, ...)
|
||||
end
|
||||
|
||||
print(f(1, 2, 3, 4))
|
||||
7
exercises/ch06/ex6_3.lua
Normal file
7
exercises/ch06/ex6_3.lua
Normal file
@@ -0,0 +1,7 @@
|
||||
local function f(...)
|
||||
local t = table.pack(...)
|
||||
return table.unpack(t, 1, t.n - 1)
|
||||
end
|
||||
|
||||
print(f(1, 2, 3, 4))
|
||||
print(f("a", "b", "c", "d"))
|
||||
34
exercises/ch06/ex6_4.lua
Normal file
34
exercises/ch06/ex6_4.lua
Normal file
@@ -0,0 +1,34 @@
|
||||
local function shuffle(l)
|
||||
for i = 1, #l do
|
||||
local new_i = math.random(1, #l)
|
||||
local tmp = l[new_i]
|
||||
l[new_i] = l[i]
|
||||
l[i] = tmp
|
||||
end
|
||||
end
|
||||
|
||||
local function table_str(t)
|
||||
local str = "{"
|
||||
for _, v in pairs(t) do
|
||||
if type(v) == "string" then
|
||||
v = '"' .. v .. '"'
|
||||
end
|
||||
str = ("%s %s,"):format(str, v)
|
||||
end
|
||||
|
||||
str = str .. " }"
|
||||
|
||||
return str
|
||||
end
|
||||
|
||||
local function test(l)
|
||||
local str = ("%s -> "):format(table_str(l))
|
||||
shuffle(l)
|
||||
str = str .. table_str(l)
|
||||
print(str)
|
||||
end
|
||||
|
||||
math.randomseed(os.time())
|
||||
|
||||
test({ 1, 2, 3, 4 })
|
||||
test({ "a", "b", "c", "d" })
|
||||
Reference in New Issue
Block a user