bugfix: keep definition keys up to date

I connect keys and values bidirectionally ways inside Definitions:
  * Definitions is a table, and the key points at the value.
  * Each value (node; a table) also contains the corresponding key.

However, before this commit I was not updating the key inside the node
when I was moving nodes around inside Definitions. And that was leading
to errors when I moved nodes around the surface like:

  Error: [string "REPL"]:12: attempt to index local 'node' (a nil value)
  stack traceback:
    [string "REPL"]:12: in function 'A1'
    [string "REPL"]:22: in function 'update'
    main.lua:196: in function 'update'
    app.lua:99: in function <app.lua:85>
    [C]: in function 'xpcall'
    app.lua:113: in function <app.lua:112>
    [C]: in function 'xpcall'

Why did I make this mistake? Because it's been easy to forget about
node.key.
This commit is contained in:
Kartik K. Agaram 2023-10-30 22:35:58 -07:00
parent c512c1a6ba
commit fbb45f2f0e
1 changed files with 5 additions and 0 deletions

View File

@ -6,18 +6,23 @@ maybe_update_key_in_definitions = function(old_definition_name, definition_name,
--print('found at index', pos)
assert(pos)
table.remove(Definitions, pos)
for i,n in ipairs(Definitions) do n.key = i end
elseif Definitions[old_definition_name] == node then
--print('found at key', old_definition_name)
Definitions[old_definition_name] = nil
end
-- at this point we're sure node is no longer in Definitions
node.key = nil
if definition_name and Definitions[definition_name] == nil then
--print('moving to key', definition_name)
Definitions[definition_name] = node
node.key = definition_name
elseif definition_name == nil or Definitions[definition_name] then
-- temporary collision; try again later
-- deleting and reinserting is inefficient, but hopefully rare
--print('moving to index', #Definitions+1)
table.insert(Definitions, node)
node.key = #Definitions
end
--print('-- definition keys')
--for k in pairs(Definitions) do