utils.lua
View source code here on GitHub!
- get_data_file(name, mode)
- Returns:
The contents of a file in
/_data
- Return type:
string
- get_answer(id)
- Returns:
The answer to a specific problem, as stored in
/_data/answers.tsv
- Return type:
number | string
1local function get_data_file(name, mode)
2 local filename = "../_data/" .. name
3 local file = io.open(filename, mode)
4
5 if not file then
6 print("Could not open file: " .. filename)
7 return
8 end
9
10 local contents = file:read("*a") -- Read all contents
11 file:close()
12 return contents
13end
14
15local function get_answer(id)
16 local id_str = tostring(id)
17 for line in string.gmatch(get_data_file("answers.tsv", "r"), "[^\r\n]+") do
18 local row = {} -- {id, type, length, value}
19 for val in string.gmatch(line, "[^\t]+") do
20 table.insert(row, val)
21 end
22 if id_str == row[1] then
23 local type_ = row[2]
24 local length = tonumber(row[3])
25 local value = row[4]
26
27 if type_ == 'str' then
28 return value
29 elseif type_ == 'int' then
30 return tonumber(value)
31 elseif type_ == 'uint' then
32 if length < 64 then
33 return tonumber(value)
34 end
35 local parsed = tonumber(value)
36 if tostring(parsed) == value then
37 return parsed
38 end
39 return nil, "Value too big to properly parse"
40 end
41 end
42 end
43 return nil, "Answer not found"
44end
45
46return {
47 get_data_file = get_data_file,
48 get_answer = get_answer,
49}