1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 | -- This file contains helper functions that work on any Nomsu value: converting values
-- to text and comparing them.
is_plain_table = (t)-> type(t) == 'table' and getmetatable(t) == nil
local fields_as_text
-- Convert a value to text. Text inside a table (when `seen` is passed in) is quoted,
-- the way it looks in Nomsu code.
as_text = (x, seen)->
return x and "yes" or "no" if type(x) == 'boolean'
return x\as_lua! if seen and type(x) == 'string'
return fields_as_text(x, seen) if is_plain_table(x)
return tostring(x)
-- Format a table's own keys and values as a Nomsu table literal, regardless of
-- its metatable.
fields_as_text = (x, seen={})->
return "{...}" if seen[x]
seen[x] = true
bits = {}
i = 1
for k,v in pairs x
if k == i
i += 1
table.insert bits, as_text(v, seen)
continue
key = if type(k) == 'string' and k\match("^[a-zA-Z_][a-zA-Z0-9_]*$")
k
elseif type(k) == 'number' and k % 1 == 0
tostring(k)
elseif type(k) == 'string'
as_text(k, seen)
else
"(#{as_text(k, seen)})"
bits[#bits+1] = if v == true then ".#{key}"
else ".#{key} = #{as_text(v, seen)}"
seen[x] = nil
return "{"..table.concat(bits, ", ").."}"
-- Structural equality: plain tables are equal if they have the same keys and
-- deeply equal values. Anything else is compared with Lua's `==`, so objects with
-- an __eq metamethod (or none) behave as usual.
deep_equal = (a, b)->
return true if rawequal(a, b)
return a == b unless is_plain_table(a) and is_plain_table(b)
for k,v in pairs(a)
return false unless deep_equal(v, b[k])
for k in pairs(b)
return false if a[k] == nil
return true
return {:fields_as_text, :as_text, :deep_equal}
|