ch05 exercises
This commit is contained in:
35
exercises/ch05/ex5_6.lua
Normal file
35
exercises/ch05/ex5_6.lua
Normal file
@@ -0,0 +1,35 @@
|
||||
local function is_sequence(t)
|
||||
local prev_k = 0
|
||||
for k, _ in pairs(t) do
|
||||
if type(k) ~= "number" or k ~= prev_k + 1 then
|
||||
return false
|
||||
end
|
||||
|
||||
prev_k = prev_k + 1
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
local function table_str(t)
|
||||
local str = "{"
|
||||
for k, v in pairs(t) do
|
||||
if type(k) == "string" then
|
||||
k = '"' .. k .. '"'
|
||||
end
|
||||
str = ("%s [%s] = %s,"):format(str, k, v)
|
||||
end
|
||||
|
||||
str = str .. " }"
|
||||
|
||||
return str
|
||||
end
|
||||
|
||||
local function test(t)
|
||||
print(("%s: %q"):format(table_str(t), is_sequence(t)))
|
||||
end
|
||||
|
||||
test({ 1, 2, 3, word = "a word", [10] = 999 })
|
||||
test({ 1, 2, 3 })
|
||||
test({ [1.0] = 1, [2] = 2 })
|
||||
test({ [1.1] = 1, [2] = 2 })
|
||||
Reference in New Issue
Block a user