Debian Codegraph @

CorsixTH/Lua/utility.lua

raw
1 --[[ Copyright (c) 2009 Peter "Corsix" Cawley
2
3 Permission is hereby granted, free of charge, to any person obtaining a copy of
4 this software and associated documentation files (the "Software"), to deal in
5 the Software without restriction, including without limitation the rights to
6 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 of the Software, and to permit persons to whom the Software is furnished to do
8 so, subject to the following conditions:
9
10 The above copyright notice and this permission notice shall be included in all
11 copies or substantial portions of the Software.
12
13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 SOFTWARE. --]]
20
21 local lfs = require("lfs")
22
23 --[[ Iterator factory for iterating over the deep children of a table.
24 For example: for fn in values(_G, "*.remove") do fn() end
25 Will call os.remove() and table.remove()
26 There can be multiple wildcards (asterisks).
27 --]]
28 function values(root_table, wildcard)
29 local wildcard_parts = {}
30 for part in wildcard:gmatch("[^.]+") do
31 wildcard_parts[#wildcard_parts + 1] = part
32 end
33 local keys = {}
34 local function f()
35 local value = root_table
36 local nkey = 1
37 for _, part in ipairs(wildcard_parts) do
38 if part == "*" then
39 local key = keys[nkey]
40 if nkey >= #keys then
41 key = next(value, key)
42 keys[nkey] = key
43 if key == nil then
44 if nkey == 1 then
45 return nil
46 else
47 return f()
48 end
49 end
50 end
51 value = value[key]
52 nkey = nkey + 1
53 else
54 if type(value) ~= "table" then
55 local mt = getmetatable(value)
56 if not mt or not mt.__index then
57 return f()
58 end
59 end
60 value = value[part]
61 if value == nil then
62 return f()
63 end
64 end
65 end
66 return value
67 end
68 return f
69 end
70
71 --! Check whether the table is empty.
72 --!return (bool) Whether the table has no entries of any kind.
73 function isTableEmpty(table)
74 return next(table) == nil
75 end
76
77 --! Get a random item from an array.
78 --!param array Array with 0 or more items.
79 --!return (nil or an item)
80 function getRandomEntryFromArray(array)
81 if #array == 0 then return nil end
82 if #array == 1 then return array[1] end
83 return array[math.random(1, #array)]
84 end
85
86 -- Variation on loadfile() which allows for the loaded file to have global
87 -- references resolved in supplied tables. On failure, returns nil and an
88 -- error. On success, returns the file as a function just like loadfile() does
89 -- with the difference that the first argument to this function should be a
90 -- table in which globals are looked up and written to.
91 -- Note: Unlike normal loadfile, this version also accepts files which start
92 -- with the UTF-8 byte order marker
93 function loadfile_envcall(filename)
94 -- Read file contents
95 local f, err = io.open(filename)
96 if not f then
97 return nil, err
98 end
99 local result = f:read(4)
100 if result == "\239\187\191#" then
101 -- UTF-8 BOM plus Unix Shebang
102 result = f:read("*a"):gsub("^[^\r\n]*", "", 1)
103 elseif result:sub(1, 3) == "\239\187\191" then
104 -- UTF-8 BOM
105 result = result:sub(4,4) .. f:read("*a")
106 elseif result:sub(1, 1) == "#" then
107 -- Unix Shebang
108 result = (result .. f:read("*a")):gsub("^[^\r\n]*", "", 1)
109 else
110 -- Normal
111 result = result .. f:read("*a")
112 end
113 f:close()
114 return loadstring_envcall(result, "@" .. filename)
115 end
116
117 if _G._VERSION == "Lua 5.1" then
118 function loadstring_envcall(contents, chunkname)
119 -- Lua 5.1 has setfenv(), which allows environments to be set at runtime
120 local result, err = loadstring(contents, chunkname)
121 if result then
122 return function(env, ...)
123 setfenv(result, env)
124 return result(...)
125 end
126 else
127 return result, err
128 end
129 end
130 else
131 function loadstring_envcall(contents, chunkname)
132 -- Lua 5.2+ lacks setfenv()
133 -- load() still only allows a chunk to have an environment set once, so
134 -- we give it an empty environment and use __[new]index metamethods on it
135 -- to allow the same effect as changing the actual environment.
136 local env_mt = {}
137 local result, err = load(contents, chunkname, "bt", setmetatable({}, env_mt))
138 if result then
139 return function(env, ...)
140 env_mt.__index = env
141 env_mt.__newindex = env
142 return result(...)
143 end
144 else
145 return result, err
146 end
147 end
148 end
149
150 -- Make pairs() and ipairs() respect metamethods (they already do in Lua 5.2)
151 do
152 local metamethod_called = false
153 pairs(setmetatable({}, {__pairs = function() metamethod_called = true end}))
154 if not metamethod_called then
155 local next = next
156 local getmetatable = getmetatable
157 pairs = function(t) -- luacheck: ignore 121
158 local mt = getmetatable(t)
159 if mt then
160 local __pairs = mt.__pairs
161 if __pairs then
162 return __pairs(t)
163 end
164 end
165 return next, t
166 end
167 end
168 metamethod_called = false
169 ipairs(setmetatable({}, {__ipairs = function() metamethod_called = true end}))
170 if not metamethod_called then
171 local ipairs_orig = ipairs
172 ipairs = function(t) -- luacheck: ignore 121
173 local mt = getmetatable(t)
174 if mt then
175 local __ipairs = mt.__ipairs
176 if __ipairs then
177 return __ipairs(t)
178 end
179 end
180 return ipairs_orig(t)
181 end
182 end
183 end
184
185 -- Helper functions for flags
186 -- NB: flag must be a SINGLE flag, i.e. a power of two: 1, 2, 4, 8, ...
187
188 -- Check if flag is set in flags
189 function flag_isset(flags, flag)
190 flags = flags % (2*flag)
191 return flags >= flag
192 end
193
194 -- Set flag in flags and return new flags (unchanged if flag was already set).
195 function flag_set(flags, flag)
196 if not flag_isset(flags, flag) then
197 flags = flags + flag
198 end
199 return flags
200 end
201
202 -- Clear flag in flags and return new flags (unchanged if flag was already cleared).
203 function flag_clear(flags, flag)
204 if flag_isset(flags, flag) then
205 flags = flags - flag
206 end
207 return flags
208 end
209
210 -- Toggle flag in flags, i.e. set if currently cleared, clear if currently set.
211 function flag_toggle(flags, flag)
212 return flag_isset(flags, flag) and flag_clear(flags, flag) or flag_set(flags, flag)
213 end
214
215 -- Various constants
216 DrawFlags = {}
217 DrawFlags.FlipHorizontal = 2^0
218 DrawFlags.FlipVertical = 2^1
219 DrawFlags.Alpha50 = 2^2
220 DrawFlags.Alpha75 = 2^3
221 DrawFlags.AltPalette = 2^4
222 DrawFlags.EarlyList = 2^10
223 DrawFlags.BoundBoxHitTest = 2^12
224 DrawFlags.Crop = 2^13
225 DrawFlags.Nearest = 2^14
226
227 -- Order of animations within a tile. Animations with a smaller number are
228 -- drawn first.
229 DrawingLayers = {}
230 DrawingLayers.Litter = 0
231 DrawingLayers.Door = 0
232 DrawingLayers.RatHole = 0
233 DrawingLayers.NorthSideObject = 1
234 DrawingLayers.WestSideObject = 2
235 DrawingLayers.AtomAnalyser = 3
236 DrawingLayers.ReceptionistFacingUser = 3 -- Facing east or south.
237 DrawingLayers.Entity = 4 -- All 'normal' animations.
238 DrawingLayers.ReceptionistFacingAway = 5 -- Facing west or north.
239 DrawingLayers.MachineSmoke = 6 -- smoke animation should be in front of machine (entity)
240 DrawingLayers.FloatingDollars = 7
241 DrawingLayers.EastSideObject = 8
242 DrawingLayers.SouthSideObject = 9
243
244 -- Keep in sync with animation_effect in th_gfx_common.h
245 AnimationEffect = {}
246 AnimationEffect.None = 0
247 AnimationEffect.Glowing = 1
248 AnimationEffect.Jelly = 2
249
250 -- Predefined colours
251 Colours = {}
252 Colours.PanelDefault = { -- CorsixTH's default panel colour (pale purple)
253 red = 154, green = 146, blue = 198
254 }
255 Colours.Disabled = { -- Specific grey with purplish aspect
256 red = 127, green = 123, blue = 149
257 }
258 Colours.Setting = Colours.PanelDefault
259 Colours.SettingHover = { -- Slightly darkened from a pale purple
260 red = 133, green = 128, blue = 183,
261 }
262 Colours.SettingActive = Colours.SettingHover
263 Colours.HotkeyBox = { -- Purple
264 red = 081, green = 076, blue = 150,
265 }
266 Colours.HotkeyBoxActive = { -- Deep purple
267 red = 041, green = 036, blue = 090,
268 }
269 Colours.Textbox = { -- Black
270 red = 000, green = 000, blue = 000
271 }
272 Colours.Scrollbar = { -- Purple
273 red = 081, green = 076, blue = 150,
274 }
275 Colours.Title = { -- Very pale purple
276 red = 174, green = 166, blue = 218
277 }
278 Colours.Caption = { -- Murky purple
279 red = 134, green = 126, blue = 178
280 }
281 Colours.AdviserPanelBackground = { -- Aqua Blue
282 red = 060, green = 174, blue = 201
283 }
284 Colours.AdviserPanelHighlight = {
285 red = 047, green = 154, blue = 190
286 }
287 Colours.AdviserPanelShadow = {
288 red = 036, green = 138, blue = 158
289 }
290 Colours.AdviserPanelDeleteButton = {
291 red = 219, green = 036, blue = 036
292 }
293
294 -- Include the standard colours also
295 Colours.White = {
296 red = 255, green = 255, blue = 255
297 }
298 Colours.Black = {
299 red = 000, green = 000, blue = 000
300 }
301 Colours.Red = {
302 red = 255, green = 000, blue = 000
303 }
304 Colours.Green = {
305 red = 000, green = 255, blue = 000
306 }
307 Colours.Blue = {
308 red = 000, green = 000, blue = 255
309 }
310 Colours.Magenta = {
311 red = 255, green = 000, blue = 255
312 }
313 Colours.Cyan = {
314 red = 000, green = 255, blue = 255
315 }
316 Colours.Yellow = {
317 red = 255, green = 255, blue = 000
318 }
319
320 -- Compare values of two simple (non-nested) tables
321 function compare_tables(t1, t2)
322 local count1 = 0
323 for k, v in pairs(t1) do
324 count1 = count1 + 1
325 if t2[k] ~= v then return false end
326 end
327 local count2 = 0
328 for _, _ in pairs(t2) do
329 count2 = count2 + 1
330 end
331 if count1 ~= count2 then return false end
332 return true
333 end
334
335 -- Convert a list to a set
336 function list_to_set(list)
337 local set = {}
338 for _, v in ipairs(list) do
339 set[v] = true
340 end
341 return set
342 end
343
344 --! Find the smallest bucket with its upper value less or equal to a given number,
345 --! and return the value of the bucket, or its index.
346 --!param number (number) Value to accept by the bucket.
347 --!param buckets (list) Available buckets, pairs of {upper=x, value=y} tables,
348 -- in increasing x value, where nil is taken as infinite. The y value is
349 -- returned for the first bucket in the list where number <= x (in normal mode).
350 -- If y is nil, the index of the bucket in the list is returned.
351 --!param alt_mode (boolean) If true, the comparison becomes number < x instead.
352 --!return (number) Value or index of the matching bucket.
353 function rangeMapLookup(number, buckets, alt_mode)
354 local function boundaryCheck(upper)
355 return alt_mode and upper > number or upper >= number
356 end
357
358 for index, bucket in ipairs(buckets) do
359 if not bucket.upper or boundaryCheck(bucket.upper) then
360 return bucket.value or index
361 end
362 end
363 assert(false) -- Should never get here.
364 end
365
366 -- this is a pseudo bitwise OR operation
367 -- assumes value2 is always a power of 2 (limits carry errors in the addition)
368 -- mimics the logic of hasBit with the addition if bit not set
369 --!param value1 (int) value to check set bit of
370 --!param value2 (int) power of 2 value - bit enumeration
371 --!return (int) value1 and value2 'bitwise' or.
372 function bitOr(value1, value2)
373 return value1 % (value2 + value2) >= value2 and value1 or value1 + value2
374 end
375
376 --! Check bit is set
377 --!param value (int) value to check set bit of
378 --!param bit (int) 0-base index of bit to check
379 --!return (boolean) true if bit is set.
380 function hasBit(value, bit)
381 local p = 2 ^ bit
382 return value % (p + p) >= p
383 end
384
385 --! Convert an array table to a string.
386 --! Joins each elements by the provided separator. As a convenience feature
387 --! if the input is not an array it will be converted to a string and
388 --! returned.
389 --!param array (table) array to join.
390 --!param separator (string) separator between elements.
391 --!return (string) The joined string.
392 function array_join(array, separator)
393 separator = separator or ","
394
395 if type(array) ~= "table" then
396 return tostring(array)
397 end
398
399 if array[1] == nil then
400 return ""
401 end
402
403 local result = tostring(array[1])
404 local i = 2
405 while array[i] ~= nil do
406 result = result .. separator
407 result = result .. tostring(array[i])
408 i = i + 1
409 end
410
411 return result
412 end
413
414 --! Merge tables in one table
415 function table_merge(...)
416 local result = {}
417 for _, t in ipairs({...}) do
418 for _, v in ipairs(t) do
419 table.insert(result, v)
420 end
421 end
422 return result
423 end
424
425 --! Checks if the table contains item
426 function table_contains(table, value)
427 for _, val in pairs(table) do
428 if val == value then
429 return true
430 end
431 end
432 return false
433 end
434
435 local function serialize_string(val, options)
436 local level = options and options.long_bracket_level_start or 0
437 while string.find(val, ']' .. string.rep('=', level) .. ']') do
438 level = level + 1
439 end
440
441 return '[' .. string.rep('=', level) .. '[' .. val .. ']' .. string.rep('=', level) .. ']'
442 end
443
444 -- Helper function to print the contents of a table. Child tables are printed recursively.
445 -- Call without specifying depth, only obj and (if wished) max_depth.
446 local function serialize_table(obj, options, depth, pt_reflist)
447 -- Used to prevent infinite loops
448 pt_reflist = pt_reflist or {}
449 options = options or {detect_cycles = true} -- By default, don't crash on cycles.
450 depth = depth or 1
451
452 if options.max_depth and depth > options.max_depth then
453 return "{...}"
454 end
455
456 for _, ref in ipairs(pt_reflist) do
457 if ref == obj then
458 if options.detect_cycles then
459 return "<reference loop>"
460 elseif not options.max_depth then
461 assert("Infinite loop detected. Specify detect_cycles or max_depth when serializing tables that may contain cycles")
462 end
463 end
464 end
465 pt_reflist[#pt_reflist + 1] = obj
466
467 local first = true
468 local indent = string.rep(" ", depth * 2)
469 local result = "{"
470 local max_array_index = 0
471 for i, v in ipairs(obj) do
472 max_array_index = i
473 if not first then
474 result = result .. ","
475 end
476 first = false
477 if options.pretty then
478 result = result .. "\n" .. indent
479 end
480 result = result .. serialize(v, options, depth + 1, pt_reflist)
481 end
482
483 for k, v in pairs(obj) do
484 if not(type(k) == "number" and k >= 1 and k <= max_array_index) then
485 if not first then
486 result = result .. ','
487 end
488 first = false
489 if options.pretty then
490 result = result .. '\n' .. indent
491 end
492
493 result = result .. "[ "
494 result = result .. serialize(k, options, depth + 1, pt_reflist)
495 result = result .. " ]="
496 result = result .. serialize(v, options, depth + 1, pt_reflist)
497 end
498 end
499 indent = string.rep(" ", (depth - 1) * 2)
500
501 if options.pretty then
502 result = result .. '\n' .. indent
503 end
504 result = result .. "}"
505
506 return result
507 end
508
509 --! Serialize a value. Call it with the value to serialize and print the output.
510 -- By default it will end recursion when a cycle is detected.
511 --!param val Value to serialize.
512 --!param options Option settings, table, 'detect_cycles' field boolean that
513 -- ends recursion on a cycle, and 'max_depth' integer that ends recursion at the
514 -- specified depth. By default initialized with "{detect_cycles = True}"
515 -- 'long_bracket_level_start' field integer that sets the starting long bracket level for escaping strings.
516 -- If not set, level zero is used.
517 --!param depth Recursion depth, should be omitted.
518 --!param pt_reflist Seen nodes, should be omitted.
519 --!return The serialized output.
520 function serialize(val, options, depth, pt_reflist)
521 if type(val) == "string" then
522 return serialize_string(val, options)
523 elseif type(val) == "table" then
524 return serialize_table(val, options, depth, pt_reflist)
525 else
526 return tostring(val)
527 end
528 end
529
530 --! Simplified interface for serializing a value with option for depth
531 -- See serialize for further explanation
532 -- Output is dumped to the console
533 --!param value A table or string to inspect
534 --!param depth (num) Optional, defaults at 1
535 function inspect(value, depth)
536 print(serialize(value, {detect_cycles = true, max_depth = depth or 1, pretty = true}))
537 end
538
539 -- Clones a table, but only the first level.
540 function shallow_clone(tbl)
541 if type(tbl) ~= "table" then return tbl end
542 local meta = getmetatable(tbl)
543 local target = {}
544 for k, v in pairs(tbl) do
545 target[k] = v
546 end
547 setmetatable(target, meta)
548 return target
549 end
550
551 --! Complete key removal and pause collection for the duration of the function
552 --! call.
553 --!
554 --! Note that the function is run as a pcall, so any error will be caught and
555 --! returned.
556 --!param fn (function) Function to call while GC is paused.
557 --!param ... Arguments to pass to fn.
558 function pause_gc_and_use_weak_keys(fn, ...)
559 -- In Lua 5.2 and later tables with weak keys (__mode = "k") may hold keys
560 -- that have already been finalized. According to the Lua reference manual
561 -- the objects are marked and finalized in one cycle and collected and
562 -- removed from the weak table keys in the next cycle. So to ensure that
563 -- all finalized keys are removed from weak tables we need to run GC for 2
564 -- complete cycles. We then stop the GC to prevent it from running during
565 -- the function call to ensure that pairs on weak tables work as expected.
566 -- Finally we restart the GC after the function call.
567 collectgarbage()
568 collectgarbage()
569 collectgarbage("stop")
570 local res = {pcall(fn, ...)}
571 collectgarbage("restart")
572
573 return unpack(res)
574 end
575
576 --! Strip trailing slashes from a path.
577 --!param path (string) The path to strip.
578 --!return (string) The path without trailing slashes.
579 function stripTrailingSlashes(path)
580 -- Remove one or more trailing / or \ characters
581 return path:gsub("[/\\]+$", "")
582 end
583
584 --! Checks if a given path is a directory.
585 --! param path (string) The path to check.
586 --! return (boolean) True if the path is a directory, false otherwise.
587 function isDirectory(path)
588 return lfs.attributes(path, "mode") == "directory"
589 end
590
591 --! Checks if a given path is a directory and can be opened.
592 --! param path (string) The path to check.
593 --! return (boolean) True if the path is a directory and is accessible, false otherwise.
594 function canOpenDirectory(path)
595 local ok, _ = pcall(lfs.dir, path)
596 return ok
597
598 -- "lfs.dir()" will throw an error if the directory isn't accessible/doesn't exist
599 -- (it does the same job of the "isDirectory()" function, but also checks if the directory can be opened)
600 end
601
602 -- Tracy Profiler stubs
603 if not tracy then
604 local function noop() end
605 tracy = {
606 ZoneBegin = noop,
607 ZoneBeginN = noop,
608 ZoneBeginS = noop,
609 ZoneBeginNS = noop,
610 ZoneEnd = noop,
611 Message = noop
612 }
613 end